Home > Back-end >  How to re-create a "crosstab plot" showing proportions using ggplot2?
How to re-create a "crosstab plot" showing proportions using ggplot2?

Time:07-01

I would greatly appreciate any help with re-creating this "crosstab plot" showing proportions:

enter image description here (source: PEW)

I guess the way is to use geom_point with the appropriate shape, but I cant really get any further than this

library(ggplot2)
df <- data.frame (col  = c("A","A","B","B"),
                  row = c("C", "D","C","D"),
                  val = c(4,10,29,31))

ggplot(df, aes(y = row, x = col))   geom_point(size = df$val, shape = 15)

Thanks for any pointers.

CodePudding user response:

I think geom_rect() might be more appropriate than geom_point() for this purpose. To get this to work, one first needs to decide what goes on the left/right, top/bottom of the plot. Below, we do that by finding a sign for a category.

library(ggplot2)
df <- data.frame (col  = c("A","A","B","B"),
                  row = c("C", "D","C","D"),
                  val = c(4,10,29,31))

df <- transform(
  df,
  sign_col = ifelse(col == "A", -1, 1),
  sign_row = ifelse(row == "C", -1, 1)
)

Then you can multiply the sign with coordinates to get the plot you might like.

ggplot(df)  
  geom_rect(
    aes(xmin = 0, xmax = sign_col * val,
        ymin = 0, ymax = sign_row * val,
        fill = factor(val))
  )  
  geom_text(
    aes(label = val,
        x = 0.5 * sign_col * val,
        y = 0.5 * sign_row * val)
  )  
  geom_hline(yintercept = 0)  
  geom_vline(xintercept = 0)  
  coord_equal()

Created on 2022-07-01 by the reprex package (v2.0.0)

  • Related