在条形图的顶部添加带有均值标签的±SE标签?

时间:2020-07-02 20:38:26

标签: r ggplot2 bar-chart

我正在尝试在条形图中的条形顶部添加文本中的平均值±标准误差值 。像Excel一样,排序... 我有这个意思,但是我也找不到设法添加标准误差值(甚至更少的“±”符号)的方法。

有办法吗?

这是我现在的数据(nh1),代码和图形。

dput(nh1)
traitement  N nombre_moules         sd         se         ci
1           canard 12    33.7500000 53.0696369 15.3198846 33.7188386
2       canard_lam  9    37.2222222 48.8102904 16.2700968 37.5189105
3              lam  9     0.4444444  0.5270463  0.1756821  0.4051236
4            nouee 12     0.8333333  1.4034589  0.4051437  0.8917153
5     nouee_canard  9   119.2222222 37.1274083 12.3758028 28.5386523
6 nouee_canard_lam 12    83.3333333 58.3225098 16.8362584 37.0563548
7        nouee_lam  9     4.3333333  4.3011626  1.4337209  3.3061663
8           temoin 12     0.5833333  1.2401124  0.3579896  0.7879298

谢谢您的帮助!

    nh1 <- summarySE(data = my_data_nombremoules, measurevar="nombre_moules", groupvars="traitement")
nh1

nh1$traitement <- factor(nh1$traitemeent)

ggplot(nh1, aes(x = traitement, y=nombre_moules
                                , fill=factor(traitement))) + 
  geom_bar(position=position_dodge(), stat="identity") +
  geom_errorbar(aes(ymin=nombre_moules-se, ymax=nombre_moules+se),
                width=.2,                    
                position=position_dodge(.9))

nh2 <- ggplot(nh1, aes(x = traitement, y=nombre_moules,
                        fill=factor(traitement))) + 
  geom_bar(position=position_dodge(), stat="identity") +
  geom_errorbar(aes(ymin=nombre_moules-se, ymax=nombre_moules+se),
                width=.2, position=position_dodge(.9)) + 
  stat_summary(fun=mean, colour="black", geom="point", size=2,show.legend = FALSE) +
  stat_summary(fun=mean, colour="black", geom="text",size=4, show.legend = FALSE, 
               vjust=-0.7, aes( label=round(nombre_moules, digits=1))) 

Graph I have for now

(在旁注中,我尝试使用geom_text而不是stat_summary作为均值标签,但是我无法减少位数为digits = 1的位数,这给了我“审美未知”错误...)< / p>

1 个答案:

答案 0 :(得分:1)

不清楚您为什么在这里使用stat_summary,因为您的数据已经汇总。您可以直接使用geom_pointgeom_text

由于您没有在问题中提供原始数据,因此我不得不尝试从您的地块中回收您的数据(请参阅本答案结尾处使用的数据)

我必须在评论中同意DJJ的意见:这看起来很混乱,并带有SE标签。我在这里选择的是geom_label而不是geom_text,以防止错误条掩盖数字。

library(ggplot2)

ggplot(nh1, aes(x = traitement, y=nombre_moules, fill = factor(traitement))) + 
  geom_col() +
  geom_errorbar(aes(ymin = nombre_moules - se, ymax = nombre_moules + se), width =.2) + 
  geom_label(aes(label = paste(nombre_moules, "\ub1", se)), nudge_y = 5, size = 4,
             label.size = 0, label.r = unit(0, "pt"), fill = "#ebebeb") +
  geom_point(size = 3) +
  theme(legend.position = "none", axis.text.x = element_blank()) +
  labs(x = NULL, y = NULL)


使用的数据

nh1 <- structure(list(traitement = c("a", "b", "c", "d", "e", "f", "g", "h"), 
                      nombre_moules = c(33.8, 37.2, 0.4, 0.8, 119.2, 83.3, 4.3, 0.6), 
                      se = c(16, 16, 0.05, 0.05, 13, 17, 1, 0.1)), 
                 class = "data.frame", row.names = c(NA, -8L))

reprex package(v0.3.0)于2020-07-02创建