Search code examples
rggplot2gridrectangles

create a 2 x 2 graph of squares R of even segments


I am trying to create a plot of 2 x 2 squares, with figures on them

will basically be a 2x2 grid of + vs -

below produces what i want except the top squares are not the same height. Any help would be appreciated, i can't see how this is doing this.

thanks

df <- data.frame(matrix(ncol = 5, nrow = 0))
colnames(df) <- c("x", "y", "color","w","perc")

df[nrow(df) + 1,] = c("+","+","orange",1,77)
df[nrow(df) + 1,] = c("+","-","green",1,17)
df[nrow(df) + 1,] = c("-","+","red",1,27)
df[nrow(df) + 1,] = c("-","-","orange",1,37)

ggplot(df, aes(x = x, y = y, fill = color, label = perc)) +
  geom_bar(stat = "identity", width=1.0) +
  geom_text(size = 3, position = position_stack(vjust = 0.5)) +
  scale_fill_identity() + 
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

Solution

  • Sounds like you are looking for geom_tile() instead of geom_bar().

    As a side note, you may want to create your dataframe by columns rather than by rows, as the former allows you greater control over the class of each column.

    # create data frame
    df <- data.frame(
      x = c("+", "+", "-", "-"),
      y = c("+", "-", "+", "-"),
      color = c("orange", "green", "red", "orange"),
      w = rep(1, 4),
      perc = c(77, 17, 27, 37),
      stringsAsFactors = FALSE
    )
    
    # plot
    ggplot(df, aes(x = x, y = y, fill = color, label = perc)) +
      geom_tile() +
      geom_text(size = 3) +
      scale_fill_identity() + 
      theme(axis.text.x = element_text(angle = 45, hjust = 1))
    

    plot