r - 为什么用 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))
为 geom_text 添加 X 和 Y 值似乎没有帮助,例如,
geom_text(aes(x=PlatformOrder, y=ReflectiveReflectionTest, label = ReflectiveReflectionTest))
问题
如何每条仅获得一个数字标签(即该条的平均值,也是 y 轴上条的高度)?
(我已经安装并加载了帖子中的所有包,但没有找到解决方案。)
解决方案
这是使用内置数据集的问题的更简单版本。
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)
推荐阅读
- java - 即使在较低的 validateAfterInactivity 之后,Apache HTTP 客户端 org.apache.http.NoHttpResponseException
- html - 当宽度为 60% 时,在 div 中居中对齐文本
- java - 向 Minecraft Forge 1.16.5 注册实体渲染处理程序
- javascript - 如何以角度返回服务调用之外的响应?
- r - R:如何循环遍历变量列表并创建具有动态名称的新变量?
- haskell - monad-coroutine 的 MonadError 实例 任何暂停 Functor 的协程
- web-applications - HTTP 请求在“请求发送”上花费了太多时间(由 chrome devtools 提供)
- debugging - 在调试控制台中突出显示错误代码的问题 - Visual Studio Code
- jquery - 如何使选择器成为有效的选择器
- ionic-framework - Cordova 短信插件电容