绘制具有多个组的条形图

Plotting a bar chart with multiple groups

我有一个按治疗状态和分类变量 df %>% group_by(treatment, categorical_var) %>% summarise(n=n()) 分组的数据框,我正在尝试使用 ggplot 获得与图片中显示的条形图相似的条形图,其中我的 y 轴将由我的 $n$ 变量和我的 x 轴将由我的 $categorical_var$

决定

如图所示,我基本上是在尝试将两个条形图合并到同一个图中,一个用于对照组,另一个用于治疗组。关于如何执行此操作的任何帮助?

这是一个可重现的例子


example <- tribble(
  ~treatment, ~categorical_var, ~n,
  "control",            "1",    10,
  "control",            "2",    12,
  "control",            "3",     7,
  "treatment",          "1",     14,
  "treatment",          "2",     5,
  "treatment",          "3",     11,
)


ggplot(example, aes(categorical_var, n)) + 
  geom_bar(position="dodge",stat="identity") + facet_wrap(~treatment)

这是我得到的 putput,我怎样才能改变样式来得到像上面图片那样的东西?

造型总是涉及一些摆弄和试验(有时会出现错误 (;))。但通常您可能会非常接近您想要的结果,如下所示:

library(ggplot2)

ggplot(example, aes(categorical_var, n)) + 
  geom_bar(position="dodge",stat="identity") + 
  # Add some more space between groups
  scale_x_discrete(expand = expansion(add = .9)) +
  # Make axis start at zero
  scale_y_continuous(expand = expansion(mult = c(0, .05))) +
  # Put facet label to bottom 
  facet_wrap(~treatment, strip.position = "bottom") +
  theme_minimal() +
  # Styling via various theme options
  theme(panel.spacing.x = unit(0, "pt"), 
        strip.placement = "outside", 
        strip.background.x = element_blank(),
        axis.line.x = element_line(size = .1),
        panel.grid.major.y = element_line(linetype = "dotted"),
        panel.grid.major.x = element_blank(),
        panel.grid.minor = element_blank())