【问题标题】:ggplot2 multiple sub groups of a bar chartggplot2 条形图的多个子组
【发布时间】:2013-12-02 09:07:28
【问题描述】:

我正在尝试生成一个包含多个因子分组的条形图。我正在尝试创建的 excel 示例,按品种和灌溉处理分组:

我知道我可以使用facet_wrap() 生成多个图表,但我想针对多年的类似数据为同一类型的数据生成多个图表。我在本例中使用的数据示例:

Year        Trt Variety    geno yield   SE
2010-2011   Irr Variety.2   1   6807    647
2010-2011   Irr Variety.2   2   5901    761
2010-2011   Irr Variety.1   1   6330    731
2010-2011   Irr Variety.1   2   5090    421
2010-2011   Dry Variety.2   1   3953    643
2010-2011   Dry Variety.2   2   3438    683
2010-2011   Dry Variety.1   1   3815    605
2010-2011   Dry Variety.1   2   3326    584

有没有办法在 ggplot2 中创建多个分组?我已经搜索了很长时间,但还没有看到类似上面示例图的示例。

感谢您的帮助!

【问题讨论】:

  • 我认为在 ggplot2 中不可能进行多个分组(不容易做到),但this 应该会有所帮助。
  • 感谢您的欢迎,感谢您的帮助! Henrik,您的回答效果很好,我总是可以编辑标签,但这会像我需要的那样绘制图表。我不知道这里看起来像关键的交互功能。 @agstudy,感谢您的链接!看起来这将完全符合我的要求,但看起来我需要一段时间才能完成那里的代码。

标签: r ggplot2


【解决方案1】:

这可能是一个开始。

dodge <- position_dodge(width = 0.9)

ggplot(df, aes(x = interaction(Variety, Trt), y = yield, fill = factor(geno))) +
  geom_bar(stat = "identity", position = position_dodge()) +
  geom_errorbar(aes(ymax = yield + SE, ymin = yield - SE), position = dodge, width = 0.2)

更新:x 轴的标签
我已添加:
coord_cartesian,设置y轴的限制,主要是下限以避免默认扩展轴。
annotate,添加所需的标签。我对x 位置进行了硬编码,在这个相当简单的示例中我觉得可以。
theme_classic,以删除灰色背景和网格。 theme,增加下绘图边距以便为两行标签留出空间,删除默认标签。
最后一组代码:因为文本添加在 x 轴下方,它在绘图区域之外“消失”,我们需要删除“剪辑”。就是这样!

library(grid)

g1 <- ggplot(data = df, aes(x = interaction(Variety, Trt), y = yield, fill = factor(geno))) +
  geom_bar(stat = "identity", position = position_dodge()) +
  geom_errorbar(aes(ymax = yield + SE, ymin = yield - SE), position = dodge, width = 0.2) +
  coord_cartesian(ylim = c(0, 7500)) +
  annotate("text", x = 1:4, y = - 400,
           label = rep(c("Variety 1", "Variety 2"), 2)) +
  annotate("text", c(1.5, 3.5), y = - 800, label = c("Irrigated", "Dry")) +
  theme_classic() +
  theme(plot.margin = unit(c(1, 1, 4, 1), "lines"),
       axis.title.x = element_blank(),
       axis.text.x = element_blank())

# remove clipping of x axis labels
g2 <- ggplot_gtable(ggplot_build(g1))
g2$layout$clip[g2$layout$name == "panel"] <- "off"
grid.draw(g2)

【讨论】:

  • 是否可以使用scale_x_discrete() 来使事情看起来像“Variety 1 (Dry)”而不是使用手动注释?我尝试过类似scale_x_discrete(labels =paste0(Variety," (",Trt,")") 之类的方法,但是我收到错误消息Error in paste0(....) : object 'Variety' not found
猜你喜欢
  • 2021-07-26
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 2016-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多