r - How do I incorporate SE in place of SD in my bar chart error bars? Also, how do I change the order of my x-axis groups
问题描述
I have created a bar chart displaying proportion of time spent on different behaviours for groups of lemurs. However I am placed with two problems.
1) I had hoped to use standard error bars in place of my standard deviation bars. I am unsure in how to incorporate it into my existing code. My current ggplot output is as follows:
data_summary <- function(data, varname, groupnames){
require(plyr)
summary_func <- function(x, col){
c(mean = mean(x[[col]], na.rm=TRUE),
sd = sd(x[[col]], na.rm=TRUE),)
}
data_sum<-ddply(data, groupnames, .fun=summary_func,
varname)
data_sum <- rename(data_sum, c("mean" = varname))
return(data_sum)
}
df4 <- data_summary(mydata_bc, varname="Time",
groupnames=c("Group", "Behaviour"))
p <- ggplot(df4, aes(x=Behaviour, y=Time, fill=Group)) +
geom_bar(stat="identity", position=position_dodge()) +
geom_errorbar(aes(ymin=Time-sd, ymax=Time+sd), width=.2,
position=position_dodge(0.9))
2) I also had hoped to change the order of my behaviours on the x axis.
Any help would be greatly appreciated.
Current bar chart
My csv data: https://drive.google.com/file/d/1UWJoluv3MWwXoQg2zcDORDJiWuIA8j4f/view?usp=sharing
解决方案
我更换了:
sd = sd(x[[col]], na.rm=TRUE)
和:
se = sd(x[[col]], na.rm=TRUE) / sqrt(sum(!is.na(x[[col]])))
即 SD 除以长度的平方根。
您的 data_summary 函数中还有一个额外的逗号。
您可以通过重新排序因子来更改列的顺序。
mydata_bc$Behaviour <- factor(mydata_bc$Behaviour, levels = c("Resting","Feeding","Socialising","Locomotion"))
然后你就可以绘图了。
data_summary <- function(data, varname, groupnames){
require(plyr)
summary_func <- function(x, col){
c(mean = mean(x[[col]], na.rm=TRUE),
se = sd(x[[col]], na.rm=TRUE) / sqrt(sum(!is.na(x[[col]]))))
}
data_sum<-ddply(data, groupnames, .fun=summary_func,
varname)
data_sum <- rename(data_sum, c("mean" = varname))
return(data_sum)
}
mydata_bc$Behaviour <- factor(mydata_bc$Behaviour, levels = c("Resting","Feeding","Socialising","Locomotion"))
df4 <- data_summary(mydata_bc, varname="Time",
groupnames=c("Group", "Behaviour"))
p <- ggplot(df4, aes(x=Behaviour, y=Time, fill=Group)) +
geom_bar(stat="identity", position=position_dodge()) +
geom_errorbar(aes(ymin=Time-se, ymax=Time+se), width=.2,
position=position_dodge(0.9))
推荐阅读
- docker - Grafana 发送带有错误图表图像的警报
- android - 在Android中绘制损坏的路径
- python - 如何冻结pygame窗口?
- opengl - OpenGL 中的 Bresenham 算法
- python - 类似于列表框的树视图的诅咒选择
- python - python中的分布式读写锁
- c++ - BOOT-INF/lib/*.jar 下的 Spring Boot fat/uber jar 中的 JNI C++ findClass()
- python - Visual Studio 代码 python
- chart.js - chart.js 散点图 - 数组中的数据集数据不显示数据
- properties - 在 Dafny 中表达归纳数据类型的属性