ggplot2 boxplots-如何在x轴上对因子水平进行分组(并为每组平均值添加参考线)

时间:2019-04-01 05:17:35

标签: r ggplot2 boxplot forcats

我有30种植物已经使用箱线图和软件包lwp_md显示了中午叶水势(ggplot2)的分布。但是我如何根据它们的叶子习性(例如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_mdimage

1 个答案:

答案 0 :(得分:0)

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)