r - 如何在 R 中的 ggplot 中为条形图添加误差线
问题描述
我最近尝试将误差线添加到我在 R 的 ggplot 中创建的条形图中。但是,当我查找 geom_errorbar 时,似乎唯一记录在案的方法是创建另一个包含 ymin 和 ymax 的数据框每个条形图,并使用该 stat='identity' 属性绘制条形图,这看起来很麻烦。
例如,这是出现在 geom_errorbar 帮助页面中的示例:
df <- data.frame(
trt = factor(c(1, 1, 2, 2)),
resp = c(1, 5, 3, 4),
group = factor(c(1, 2, 1, 2)),
se = c(0.1, 0.3, 0.3, 0.2)
)
df2 <- df[c(1,3),]
# Define the top and bottom of the errorbars
limits <- aes(ymax = resp + se, ymin=resp - se)
p <- ggplot(df, aes(fill=group, y=resp, x=trt))
p + geom_bar(position="dodge", stat="identity")
# Because the bars and errorbars have different widths
# we need to specify how wide the objects we are dodging are
dodge <- position_dodge(width=0.9)
p + geom_bar(position=dodge) + geom_errorbar(limits, position=dodge, width=0.25)
难道没有更好的方法来做到这一点而不必使用 stat='identity' 绘图吗?
解决方案
使用 geom_errobars 有一种更简单的方法来绘制误差线,由于某种原因,该方法没有得到很好的记录。基本上你只需要使用 stat='summary' 到 geom_errorbar 对象。
ggplot(data=mtcars, aes(x=gear, y=hp)) + geom_bar(stat='summary') + geom_errorbar(stat='summary', width=.2)
这是真的,如果您只想使用误差条来描述条形两侧的标准偏差(您可能希望使用不同的度量,如置信区间等)
推荐阅读
- c# - 如何从后台运行的控制器调用函数
- webpack - 我可以在没有服务器的情况下使用 write-file-webpack-plugin 编写文件吗?
- javascript - 如何使用 javascript 将上传的照片保存到我的 HTML 项目中
- javascript - React:在子组件中运行函数在所有同类子组件中运行函数
- css - 下拉菜单显示/隐藏
- r - R Studio 控制台中表格的颜色
- swift - Userdefaults 中的 Firebase ID
- ios - 核心数据崩溃抓取
- javascript - 为什么单击处理程序删除表行会引发错误为“未定义”?
- docker - 无法在 Docker 容器中运行命令