我使用的数据是here.
我总结了数据,然后想用它来绘制条形图。
这是我的代码:
heights<-read.csv("reading_anthesis.csv",as.is=T)
str(heights)
##DATA SUMMARY##
##code for data summary from
## http://www.cookbook-r.com/Manipulating_data/Summarizing_data/
## data: a data frame.
## measurevar: the name of a column that contains the variable to be summariezed
## groupvars: a vector containing names of columns that contain grouping variables
## na.rm: a boolean that indicates whether to ignore NA's
## conf.interval: the percent range of the confidence interval (default is 95%)
summarySE <- function(data=NULL, measurevar, groupvars=NULL, na.rm=FALSE,
conf.interval=.95, .drop=TRUE) {
require(plyr)
# New version of length which can handle NA's: if na.rm==T, don't count them
length2 <- function (x, na.rm=FALSE) {
if (na.rm) sum(!is.na(x))
else length(x)
}
# This does the summary. For each group's data frame, return a vector with
# N, mean, and sd
datac <- ddply(data, groupvars, .drop=.drop,
.fun = function(xx, col) {
c(N = length2(xx[[col]], na.rm=na.rm),
mean = mean (xx[[col]], na.rm=na.rm),
sd = sd (xx[[col]], na.rm=na.rm)
)
},
measurevar
)
# Rename the "mean" column
datac <- rename(datac, c("mean" = measurevar))
datac$se <- datac$sd / sqrt(datac$N) # Calculate standard error of the mean
# Confidence interval multiplier for standard error
# Calculate t-statistic for confidence interval:
# e.g., if conf.interval is .95, use .975 (above/below), and use df=N-1
ciMult <- qt(conf.interval/2 + .5, datac$N-1)
datac$ci <- datac$se * ciMult
return(datac)
}
summary<-summarySE(heights, measurevar="height", groupvars=c("genotype", "treatment"))
summary.2<-summary
summary.2$genotype<-factor(summary.2$genotype)
summary.2$treatment<-factor(summary.2$treatment)
pd <- position_dodge(.9)
ggplot(summary.2, aes(x=genotype, y=height, fill=genotype)) +
geom_bar(position=position_dodge(), stat=identity, colour ="black") +
geom_errorbar(aes(ymin=height-se, ymax=height+se), colour="black", width=.3, position=pd) +
ylab("Height (cm)") +
theme(axis.title = element_text(size=14,face="bold"),
axis.text = element_text(size=13),
strip.text.y = element_text(size=12))
我收到错误电话:Error in stat$parameters : object of type 'closure' is not subsettable
我无法找到我没有定义的函数/向量的位置,正如之前的帖子暗示的那样。
非常感谢任何帮助。
答案 0 :(得分:8)
这个问题很简单,但追踪它确实是一项艰巨的任务。 stat=identity
应为stat="identity"
。我还更改了fill=treatment
以获得以下图片:
ggplot(summary.2, aes(x=genotype, y=height, fill=treatment)) +
geom_bar(position=position_dodge(), stat="identity", colour="black") +
geom_errorbar(aes(ymin=height-se, ymax=height+se),
colour="black", width=.3, position=pd) +
ylab("Height (cm)") +
theme(axis.title = element_text(size=14, face="bold"),
axis.text = element_text(size=13),
strip.text.y = element_text(size=12))