r - 如何使用 ggplot2 绘制分组条形图的误差线?
问题描述
我有一个数据集,其中一个变量(bTemp)有两个不同的因素(位置和值),我根据这两个因素对数据进行分组,然后为这些数据组生成标准误差(sem)(即我生成了 st.字段最大值、实验室最大值、字段最小值等下的数据错误)。
我试图绘制圣。分组数据的错误到我的分组条形图上,但我只得到一个。每个平均条集群的误差条,而不是两个(集群中的每个平均条一个)。我检查了我的分组数据框,它正在生成 st。错误正确。所以我在geom_errorbar中定义误差线的方式一定有问题。
str(LabFieldData)
'data.frame': 324 obs. of 3 variables:
$ Place: Factor w/ 2 levels "Field","Lab": 1 1 1 1 1 1 1 1 1 1 ...
$ Value: Factor w/ 3 levels "Max","Mean","Min": 3 3 3 3 3 3 3 3 3 3 ...
$ bTemp: num 26.5 26.7 26.1 28.1 26.6 26.8 23.9 26.1 28.5 26.4 ...
#Group data by place (lab,field) and value(min,mean,max)
LabFieldData %>% group_by(Place,Value) %>%
mutate(sem = sd(bTemp)/sqrt(length(bTemp))) %>%
#Plot bar plot of means by value (mean, min, max) and color by place (lab, field)
ggplot(mapping = aes(Value, bTemp, color = Place)) +
geom_bar(mapping = aes(color = Place, fill = Place), stat = "summary", position="dodge") +
geom_errorbar(stat = 'summary', mapping = aes(ymin=bTemp-sem,ymax=bTemp+sem),
position=position_dodge(0.9),width=.1, color = "black", size = 1) +
scale_y_continuous(name = "Body Temperature (°C)", breaks = c(0,5,10,15,20,25,30,35),
limits=c(0,34)) + scale_x_discrete(name=element_blank(),limits=c("Min","Mean","Max")) +
theme(legend.title = element_blank()) + scale_color_hue()
解决方案
您非常接近,您需要在 ggplot 函数中而不是在 geom_bar 函数中指定填充。
LabFieldData %>% group_by(Place,Value) %>%
mutate(sem = sd(bTemp)/sqrt(length(bTemp))) %>%
#Plot bar plot of means by value (mean, min, max) and color by place (lab, field)
ggplot(mapping = aes(Value, bTemp, color = Place, fill=Place)) +
geom_bar(stat = "summary", position="dodge") +
geom_errorbar(stat = 'summary', mapping = aes(ymin=bTemp-sem,ymax=bTemp+sem),
position=position_dodge(0.9), width=.1, color = "black", size = 1) +
scale_y_continuous(name = "Body Temperature (°C)", breaks = c(0,5,10,15,20,25,30,35), limits=c(0,34)) +
scale_x_discrete(name=element_blank(), limits=c("Min","Mean","Max")) +
theme(legend.title = element_blank()) + scale_color_hue()
推荐阅读
- stdout - 如何使用 Python/Paramiko 脚本忽略 MOTD 和 Banner 消息?
- android - 从 git 克隆后 Gradle 建立连接超时
- google-apps-script - 如何在谷歌表格图表中显示数据系列标签
- docker - 无法提取图像“levm38/server:latest”:rpc 错误:代码 = 未知 desc = 来自守护进程的错误响应:获取 https://registry-1.docker.io/v2/:EOF
- webots - 控制 Webots 模拟步骤
- node.js - Nodemon 在尝试使用 es6 模块时崩溃,但在 es5 上运行良好
- node.js - 在猫鼬模式中使用“过期”后,集合中的项目不会自动删除
- javascript - 如何使用 { } 执行箭头函数表达式
- bash - Makefile 中的这些行是什么意思?
- javascript - 未捕获的 TypeError:this.state.map 不是函数