r - 在ggplot中调整错误栏上方的文本位置
问题描述
我有以下数据框:
df <- structure(list(Gender = c("M", "M", "M", "M", "F", "F", "F",
"F"), HGGroup = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), .Label =
c("Low: \n F: <11.5, M: <12.5",
"Medium: \n F: > 11.5 & < 13, M: >12.5 & < 14.5", "High: \n F: >= 13, M >=
14.5", "No data"), class = "factor"), MeanBlood = c(0.240740740740741,
1.20689655172414, 0.38150289017341, 0.265957446808511, 0.272727272727273,
1.07821229050279, 0.257309941520468, 0.288776796973518), SEBlood =
c(0.0694516553311722, 0.154646785911315, 0.0687932999815165,
0.0383529942166715, 0.0406072582435844, 0.0971802933392401,
0.0327856332532931, 0.0289636037703526),
N = c(108L, 116L, 173L, 376L, 319L, 179L, 342L, 793L)), row.names = c(NA,
-8L), class = c("tbl_df", "tbl", "data.frame"))
我有以下命令来绘制每组的均值和置信区间:
ggplot(df, aes(x = Gender, y = MeanBlood, colour = Gender)) +
geom_errorbar(aes(ymin = MeanBlood - SEBlood*qnorm(0.975), ymax = MeanBlood
+ SEBlood*qnorm(0.975)), width = 0.3, stat = "identity") +
geom_point(size = 3) + facet_grid(~HGGroup) + theme(legend.position =
"none") +
geom_text(aes(label = N, x = Gender), vjust = -5)
我正在尝试将文本完全放在错误栏的顶部,但是对于每个组来说,它需要位于不同的位置,并且目前看起来很奇怪。
我认为问题源于这样一个事实,即每个组的置信区间长度不同,因此恒定的理由不起作用 - 它必须相对于下四分位数。
有什么建议么?
解决方案
这似乎有效,y
您的标签的 the ,如您所愿,不是 of 中的集合y
,而是:aes
ggplot
ymax
ggplot(df, aes(x = Gender, y = MeanBlood, colour = Gender)) +
geom_errorbar(aes(ymin = MeanBlood - SEBlood*qnorm(0.975), ymax = MeanBlood
+ SEBlood*qnorm(0.975)), width = 0.3, stat = "identity") +
geom_point(size = 3) + facet_grid(~HGGroup) + theme(legend.position =
"none") +
geom_text(aes(y = MeanBlood + SEBlood*qnorm(0.975), label = N, x = Gender), vjust = -1)
如果您将 ymax 移动到ggplot
调用中,其他层将能够访问它,因此无需重新定义它:
ggplot(df, aes(x = Gender, y = MeanBlood, colour = Gender,
ymin = MeanBlood - SEBlood*qnorm(0.975), ymax = MeanBlood
+ SEBlood*qnorm(0.975))) +
geom_errorbar(aes(width = 0.3), stat = "identity") +
geom_point(size = 3) + facet_grid(~HGGroup) + theme(legend.position =
"none") +
geom_text(aes(y = stat(ymax), label = N, x = Gender), vjust = -1)
推荐阅读
- java - 如果计数器达到特定数字,如何向按钮添加声音?
- powershell - 团队:Invoke-Webrequest 向团队发送 base64 字符串 (png)
- python - 遍历numpy数组以在字典中使用
- python - Python 将回车视为换行符。我能做些什么呢?
- javascript - 比较 2 个对象数组中的特定键
- c# - 如何使用 Prism.Forms 框架从普通页面导航到 MasterDetailPage?
- deployment - 为什么在 minikube 中正确部署服务时,应用程序部署状态为“Available:0”?
- html - 如何在有课程的 td 中获取内容?
- python - Tensorflow toco 工具将 Conv2D 转换为 DepthwiseConv2DNative,但简化图不会产生与原始图相同的结果
- c++ - 为什么现代 C++ 仍然使用 int argc, char** argv 保留旧的 C 风格原型