【问题标题】:ggplot2 boxplots - How to group factors levels on the x-axis (and add reference lines for each group mean)ggplot2 boxplots - 如何在 x 轴上对因子水平进行分组(并为每个组均值添加参考线)
【发布时间】:2019-08-22 05:26:50
【问题描述】:

我有 30 种植物,我使用箱线图和包 ggplot2 显示了正午叶水势 (lwp_md) 的分布。但是我如何根据它们的叶片习性(例如DeciduousEvergreen)沿 x 轴对这些物种进行分组,并显示一条参考线,指示每个叶片习性水平的平均 lwp_md 值?

我尝试过使用 forcats 包,但真的不知道如何继续使用这个包。在网上广泛搜索后,我找不到任何东西。我似乎能做的最好的事情是通过其他一些功能对物种进行排序,例如中位数。

下面是到目前为止我的代码示例。注意我使用了 ggplot2ggthemes 包:

library(ggplot2)
ggplot(zz, aes(x=fct_reorder(species, lwp_md, fun=median, .desc=T), y=lwp_md)) +
  geom_boxplot(aes(fill=leaf_habit)) +
  theme_few(base_size=14) +
  theme(legend.position="top", 
        axis.text.x=element_text(size=8, angle=45, vjust=1, hjust =1)) +
  xlab("Species") +
  ylab("Maximum leaf water potential (MPa)") +
  scale_y_reverse() +
  scale_fill_discrete(name="Leaf habit",
                      breaks=c("DEC", "EG"),
                      labels=c("Deciduous", "Evergreen"))

这是我的数据的一个子集,包括我的 4 个物种(2 个落叶树,2 个常绿树):

> dput(zz)
structure(list(id = 1:20, species = structure(c(1L, 1L, 1L, 1L, 
1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L
), .Label = c("AMYELE", "BURSIM", "CASXYL", "COLARB"), class = "factor"), 
    leaf_habit = structure(c(2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 
    1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L), .Label = c("DEC", 
    "EG"), class = "factor"), lwp_md = c(-2.1, -2.5, -2.35, -2.6, 
    -2.45, -1.7, -1.55, -1.4, -1.55, -0.6, -2.6, -3.6, -2.9, 
    -3.1, -3.3, -2, -1.8, -2, -4.9, -5.35)), class = "data.frame", row.names = c(NA, 
-20L))

我希望如何显示、剪切和编辑数据的示例 - 我想在 x 轴上使用 species,在 y 轴上使用 lwp_md

【问题讨论】:

  • this question 的答案是否适合您的需求? (用平均值代替中位数)
  • 是的,我特别想显示平均值。可能应该编辑我的代码来表明这一点。

标签: r ggplot2 boxplot forcats


【解决方案1】:

gpplot 默认按字母顺序排列因子。为避免这种情况,您必须将它们作为有序因子提供。这可以通过安排data.frame 然后重新声明因子来完成。要生成平均值,我们可以使用 group_by 并在 df 中改变一个新的均值列,以便稍后绘制。

完整代码如下:

library(ggplot)
library(ggthemes)
library(dplyr)

zz2 <- zz %>% arrange(leaf_habit) %>%  group_by(leaf_habit) %>% mutate(mean=mean(lwp_md))
zz2$species <- factor(zz2$species,levels=unique(zz2$species))

ggplot(zz2, aes(x=species, y=lwp_md)) +
  geom_boxplot(aes(fill=leaf_habit)) +
  theme_few(base_size=14) +
  theme(legend.position="top", 
        axis.text.x=element_text(size=8, angle=45, vjust=1, hjust =1)) +
  xlab("Species") +
  ylab("Maximum leaf water potential (MPa)") +
  scale_y_reverse() +
  scale_fill_discrete(name="Leaf habit",
                      breaks=c("DEC", "EG"),
                      labels=c("Deciduous", "Evergreen")) +
  geom_errorbar(aes(species, ymax = mean, ymin = mean),
                size=0.5, linetype = "longdash", inherit.aes = F, width = 1)

【讨论】:

  • 太棒了,效果很好!您的解释非常清楚,也很容易学习。非常感谢您抽出时间 Julian_Hn。
  • 如果对你有帮助,请考虑采纳答案,让其他人也可以借鉴。
猜你喜欢
  • 2011-05-13
  • 1970-01-01
  • 2013-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-17
  • 2015-06-16
  • 1970-01-01
相关资源
最近更新 更多