如何在 R 中的同一图中并排显示条形图和堆叠条形图?

How to display side by side bar plot as well as stacked bar plot in the same figure in R?

我有以下带变量的数据集:

  1. X_rfhlth : "Good" 或 "Bad" 健康
  2. X_imprace : "Asian" “白色”, "Black" 等
  3. 性别:男、女

我想为堆叠和并排的比例创建条形图。

每对条形代表一场比赛,堆叠的条形代表健康状况好坏总和为 100%。每对条形代表男性和女性。

我该如何解决这个问题? geom_col() 允许 position="stack" 或 "dodge" 但不能同时允许两者。

使用构面。例如:

ggplot(mtcars, aes(factor(vs), mpg, fill = factor(cyl))) + 
  geom_col() + 
  facet_grid(~factor(gear))

或者,绘制相互作用图。但这通常不太好:

ggplot(mtcars, aes(interaction(vs, gear), hp, fill = factor(cyl))) + 
  geom_col()