【问题标题】:Plotting a bar chart with multiple groups绘制具有多个组的条形图
【发布时间】:2022-01-09 14:59:25
【问题描述】:

我有一个按治疗状态和分类变量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,我怎样才能改变样式以获得像上面图片一样的东西?

【问题讨论】:

标签: r ggplot2 dplyr bar-chart


【解决方案1】:

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

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())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-07
    • 2018-03-18
    • 2017-09-06
    • 2020-07-22
    • 1970-01-01
    • 1970-01-01
    • 2018-08-15
    相关资源
    最近更新 更多