首页 > 解决方案 > 为什么用 geom_text 标记 ggplot 绘图条的尝试不起作用?

问题描述

我想在条形图顶部附近显示每个条形的平均值,有点像这篇文章中的下图。

正确标记的条形图的图像

我正在使用该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, position = "dodge", 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))

y 轴上带有数字的条形图

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

geom_text(aes(x=PlatformOrder, y=ReflectiveReflectionTest, label = ReflectiveReflectionTest))

问题

如何每条仅获得一个数字标签(即该条的平均值,也是 y 轴上条的高度)?

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

标签: rggplot2dplyrbar-chartgeom-text

解决方案


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

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

在此处输入图像描述

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

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

ggplot(mtcars, aes(carb, wt, label = wt)) +
  stat_summary(geom = "bar", fun = mean, 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", fun = mean, color="black")

在此处输入图像描述

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

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

推荐阅读