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

问题描述 投票:0回答:1

我有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

r ggplot2 boxplot forcats
1个回答
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)
© www.soinside.com 2019 - 2024. All rights reserved.