geom_bar不显示平均值

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

我目前正在尝试在实验中针对每种物种/处理组合绘制变量pt的平均值。这是我正在使用的代码:

ggplot(data = data, aes(x=treat, y=pt, fill=species)) +
 geom_bar(position = "dodge", stat="identity") +
 labs(x = "Treatment", 
      y = "Proportion of Beetles on Treated Side", 
      colour = "Species") +
 theme(legend.position = "right")

R output plot

您可以看到,该图似乎假设我的5N和95E处理的平均值为1.00,这是不正确的。我不知道问题可能在哪里。

r ggplot2 geom-bar
2个回答
0
投票

据我了解,默认情况下,这不会绘制y变量的均值。您是否计算了每种治疗的费用?如果没有,我建议您在数据框中添加一列包含平均值的列。我敢肯定有一种更简单的方法可以做到这一点,但是请尝试:

data$means <- rep(NA, nrow(data))
for (x in 1:nrow(data)) {
    #assuming "treat" column is column #1 in your data fram
    data[x,ncol(data)] <- mean(which(data[,1]==data[x,1]))
}

然后尝试替换

geom_bar(position = "dodge", stat="identity")

with

geom_col(position = "dodge")

如果您的y变量已包含均值,只需将显示的geom_bar切换为geom_col即可。 stat =“ identity”的Geom_bar将对值求和而不是返回均值。


0
投票

使用tidyverse中的ggplot2tidyverse询问您的要求,

dat %>% 
  group_by(treat, species) %>% 
  summarise(mean_pt = mean(pt)) %>% 
  ungroup() %>% 
  ggplot(aes(x = treat, y = mean_pt, fill = species, group = species)) + 
  geom_bar(position = "dodge", stat = "identity")+
  labs(x = "Treatment", 
       y = "Proportion of Beetles on Treated Side", 
       colour = "Species") +
  theme(legend.position = "right") +
  geom_text(aes(label = round(mean_pt, 3)), size = 3, hjust = 0.5, vjust = 3, position =  position_dodge(width = 1))

dat是实际的数据集。我计算了mean_pt,因为这就是您要绘制的图。我还添加了geom_text片段,以便您可以查看结果并将它们与您的想法进行比较。

© www.soinside.com 2019 - 2024. All rights reserved.