簡體   English   中英

GGplot 平均值條形圖

[英]GGplot averages bar plot

我想在 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)```

要獲得每個物種存在或不存在的平均值的圖,您可以使用例如pivot_longertidyr將數據pivot_longer重塑為更長的格式,然后計算每個物種每個類別的百分比的平均值和 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繪制這個新數據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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM