如何使用 ggplot2 重新创建显示比例的“交叉表图”?

mar*_*rho 9 r ggplot2

我将非常感谢任何帮助重新创建这个显示比例的“交叉表图”:

在此输入图像描述 (来源:皮尤中心

我想方法是使用具有适当形状的 geom_point ,但我真的无法比这更进一步

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)

Run Code Online (Sandbox Code Playgroud)

感谢您的指点。

teu*_*and 11

我认为geom_rect()可能比geom_point()这个目的更合适。为了让它发挥作用,首先需要决定图的左/右、上/下发生什么。下面,我们通过查找类别的标志来做到这一点。

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)
)
Run Code Online (Sandbox Code Playgroud)

然后您可以将符号与坐标相乘以获得您可能喜欢的图。

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()
Run Code Online (Sandbox Code Playgroud)

由reprex 包于 2022 年 7 月 1 日创建(v2.0.0)