我想在ggplot中制作带有误差线的条形图。我有一列标有存在或不存在,P或A的物种,另一列标有百分比损害。我想要一张图,其中x轴上的所有物种都存在或不存在,而在y轴上存在或不存在该物种时的平均百分比。
示例数据
example$species1 = c('P','P','P','P','P','A','A','A','A','A')
example$species2 = c('P','P','A','A','P','P','A','A','P','P')
example$percent1 = c(10,20,15,21,13,50,75,60,35,44)
View(example)```
答案 0 :(得分:0)
要获取每个物种存在或不存在的平均值的图,您可以使用pivot_longer
中的tidyr
将数据框重塑为更长的格式,然后计算百分比的均值和sem每个物种的每个类别如下:
library(dplyr)
library(tidyr)
EX <- example %>% pivot_longer(cols = c(species1,species2), names_to = "var", values_to = "val") %>%
group_by(var,val) %>% summarise(Mean = mean(percent1),
SEM = sd(percent1)/sqrt(n()))
# A tibble: 4 x 4
# Groups: var [2]
var val Mean SEM
<chr> <fct> <dbl> <dbl>
1 species1 A 52.8 6.88
2 species1 P 15.8 2.08
3 species2 A 42.8 14.7
4 species2 P 28.7 6.83
然后,您可以使用ggplot
来绘制此新数据框,如下所示:
library(ggplot2)
ggplot(EX, aes(x = var, y = Mean, fill = val))+
geom_col(position = position_dodge())+
geom_errorbar(aes(ymin = Mean-SEM, ymax = Mean+SEM), position = position_dodge(0.9), width = 0.2)+
labs(x = "Species", y = "Percentage")
它回答了您的问题吗?
可复制的示例
example = data.frame(species1 = c('P','P','P','P','P','A','A','A','A','A'),
species2 = c('P','P','A','A','P','P','A','A','P','P'),
percent1 = c(10,20,15,21,13,50,75,60,35,44))