r - 如何在 ggplot 瀑布图上添加误差线?
问题描述
我想在我的瀑布图中的所有条形图中添加误差线。
这是一个示例数据和我用来创建绘图的代码:
library(dplyr)
library(ggplot2)
set.seed(100)
df<-tibble(Year= c(2001, 2001, 2001, 2001, 2002, 2002, 2002, 2002, 2003, 2003, 2003, 2003), Vals = abs(rnorm(12)*5), Affil = as.factor(c(1,2,1,2,1,2,1,2,1,2,1,2)), SD=rnorm(12, 1, 0.5))
df[c(T, T, F, F),]$Vals <- -(df[c(T, T, F, F),]$Vals)
p <- ggplot(data = df, aes(Year,Vals)) +
geom_bar(stat = "identity", aes(fill=Affil), position=position_dodge()) +
geom_errorbar(aes(ymin=Vals-SD, ymax=Vals+SD), width=.2, position=position_dodge(.9))
p + theme_bw(base_size = 16) + geom_hline(aes(yintercept=0), size=1.25)
对于每一年,应该有 2 对误差线。两个代表每年Affil
,2 个代表与每年相关的正值和负值Affil
。我尝试过内联过滤dplyr
,逐步添加错误栏,但解决方案变得繁琐且无法正常工作。
解决方案
我可以通过为错误栏分配color
美学来做到这一点:
p <- ggplot(data = df, aes(Year,Vals)) +
geom_bar(stat = "identity", aes(fill=Affil), position=position_dodge()) +
geom_errorbar(aes(ymin=Vals-SD, ymax=Vals+SD, color=Affil), width=.2, position=position_dodge(0.9))
p + theme_bw(base_size = 16) + geom_hline(aes(yintercept=0), size=1.25) +
scale_color_manual(values=c("firebrick4","darkblue"))
为了避免重叠您可以使用的误差position_jitterdodge
线,但这会产生一些奇怪的线条,对于我搜索的内容,您可以通过这样做来解决:使用 `jitterdodge` 时在 ggplot 中对齐点和误差线
推荐阅读
- flutter - 如何将 Flutter 的 ExpansionPanelList 小部件的默认框装饰更改为圆角矩形框
- docker - 仅针对 REST 请求从一个 docker 容器到另一个容器的连接被拒绝错误
- json - JSON 解析错误:意外的标识符“未定义”(React Native)
- java - 如何以易于测试的方式在 Web 服务中实例化数据源,并且可以通过特定的错误代码失败来处理?
- sas - 如何以以下格式导入 sas 日期时间
- php - 覆盖 Woocommerce 中特定运输类别的所有运输成本
- c# - C# - 控制台应用程序“拖放”崩溃
- python - 仅在 PyCharm 中尝试相对导入超出顶级包消息
- c# - Selenium c#查找元素选择元素异常
- javascript - 试图将对象数组减少为相似但汇总的对象数组