r - 使用 geom = "errorbars" 的错误栏位置错误
问题描述
正如你所看到的错误栏不在正确的位置,我不知道为什么不。以下是我使用的代码:
df_midtermclean$gender <- factor(df_midtermclean$ï..gender, labels = c('Male', 'Female'))
#reshaping from wide to long format
data_long <- melt(df_midtermclean,
# ID variables - all the variables to keep but not split apart on
id.vars=c("gender"),
# The source columns
measure.vars=c("sSkills", "sPerform", "sComplex", "sIQ" ),
# Name of the destination column that will identify the original
# column that the measurement came from
variable.name="measures",
value.name="score")
p2 <- ggplot(data_long, aes(measures, score)) + stat_summary(fun.y = mean, geom = "bar", aes(fill = gender), position = "dodge")
p2 <- p2 + stat_summary(geom = "errorbar", fun.data = mean_cl_normal, position = position_dodge(.9), width = .1)
p2 <- p2 + labs(x = "Continuous Measures", y = "Participant Scores", fill = "Gender")
p2
数据。
data_long <-
structure(list(gender = structure(c(1L, 1L, 1L,
1L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
2L, 2L, 1L, 1L, 1L), .Label = c("Male", "Female"),
class = "factor"), measures = structure(c(1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L), .Label = c("sSkills",
"sPerform", "sComplex", "sIQ"), class = "factor"),
score = c(4.75, 3, 3.5, 3.75, 3, 3.25, 3.25, 3,
2.75, 2.75, 2.5, 2.75, 3.75, 3.5, 3.75, 3.75,
3.25, 3.25, 4, 3.25)), row.names = c(NA, 20L),
class = "data.frame")
解决方案
不幸的是,您的代码无法重现!但是,我可能会在http://www.sthda.com/english/wiki/ggplot2-error-bars-quick-start-guide-r-software-and-data-visualization上找到解决方案
library(ggplot2)
df <- ToothGrowth
df$dose <- as.factor(df$dose)
# Function to calculate the mean and the standard deviation
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)
}
# New dataframe
df2 <- data_summary(ToothGrowth, varname="len",
groupnames=c("supp", "dose"))
df2$dose <- as.factor(df2$dose)
ggplot(df2, aes(x=dose, y=len, fill=supp)) +
geom_bar(stat="identity", color="black", position=position_dodge()) +
geom_errorbar(aes(ymin=len-sd, ymax=len+sd), width=.2, position=position_dodge(.9))
推荐阅读
- elixir - Elixir:当前没有与给定名称关联的进程
- scala - 如何避免对 Spark 数据帧的嵌套调用 - 这不起作用
- spring - Spring可为空的注释生成未知的枚举常量警告
- security - 将 CSRF Token 放在 GET 请求 URL 中是否有风险?
- linux - 执行脚本后始终清理 PowerShell 窗口
- django - Django:如何从数据库中获取倒数第二个对象?
- python - AttributeError:“PiRGBArray”对象没有属性“形状”
- java - 如何将某些规则应用于 JDBC 中的某些列?
- java - 无法执行 maven-surefire-plugin 但只能使用 circleci
- javascript - 在不使用指针事件的情况下防止在元素内触发 Mouseenter 和 Mouseleave