1

lwp_md我有 30 种植物,我使用箱线图和软件包展示了正午叶片水势 () 的分布ggplot2。但是我如何根据它们的叶片习性(例如 )沿 x 轴对这些物种进行分组DeciduousEvergreen并显示一条指示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))

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

4

1 回答 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)
于 2019-04-01T06:30:08.923 回答