为什么这种尝试使用 geom_text 标记 ggplot 绘图条不起作用?

问题描述

我想在条形图顶部附近显示每个条形的平均值,有点像下面来自 this post 的图像。

image of correctly labeled bar plot

我正在使用该帖子中的 geom_text 代码,但该图将变量的值放置在所有条形上,而不是将每个条形的一个平均值放置在条形顶部。

ggplot(data=SocratesPreStudyApproved,aes(x=PlatformOrder,y=ReflectiveReflectionTest,fill=PlatformOrder))+ 
  stat_summary(geom = "bar",fun = mean,position = "dodge",color="black")+
  stat_summary(geom = "errorbar",fun.data = mean_se,width=.2)+
  stat_compare_means(method = "t.test",comparisons = PlatformComparisons,label = "p.signif")+
  facet_wrap(~ReasoningPhilosophyOrder,scales="fixed",strip.position = "bottom")+
  theme_classic()+
  theme(legend.position = "none")+
  labs(title = "Analyzing only approved participants (excluding rejected)",x = "Platform within each condition order",y = "Reflective responses to reasoning items (with lures)")+
  scale_fill_grey(start = .6,end = 1)+
  geom_text(aes(label = ReflectiveReflectionTest))
@H_404_11@

bar plot with numbers up the y-axis

为 geom_text 添加 X 和 Y 值似乎没有帮助,例如,

geom_text(aes(x=PlatformOrder,label = ReflectiveReflectionTest))
@H_404_11@

问题

如何让每个条形只有一个数字标签(即该条形的平均值,也就是条形在 y 轴上的高度)?

(我已经安装并加载了帖子中的所有包,但没有找到解决方案。)

解决方法

这是使用内置数据集简化的问题版本。

ggplot(mtcars,aes(carb,wt,label = wt)) +
  stat_summary(geom = "bar",fun = mean,position = "dodge",color="black") +
  geom_text()

enter image description here

我已经告诉条形层计算平均值 wt 并显示每个 carb 的平均值。同时,文本层正在接收所有组成元素的数据,并使用它们的 wt 值作为 y 和标签。

一种选择是让文本层执行相同的汇总计算。

ggplot(mtcars,color="black") +
  # note: the ..y.. here tells ggplot to use the value after the summary calc
  stat_summary(aes(label=..y..),vjust = 0,geom = "text",color="black")

enter image description here

我个人的偏好是在 ggplot 之前执行总结,像这样,导致对相同输出的更简单的绘图调用:

mtcars %>%
  group_by(carb) %>%
  summarize(wt = mean(wt)) %>%
  ggplot(aes(carb,label = wt)) +
  geom_col() +
  geom_text(vjust = 0)