我正在尝试向条形图添加错误栏
averg <- aggregate(appxincome,by = list(educ,sex),mean)
boxplot1 <- barplot(averg$x,
xlab = "Education",
ylab = "Income",
ylim = c(0,100000),
main = "Averge Income by Education and Gender",
names.arg = c("Female College", "Female High School","Female Less Than High School","Male College", "Male High School","Male Less Than High School"),
cex.names = 0.5,
las = 2)
confint(mod1)
cis <- as.data.frame(confint(mod1))
error.bar <- function(x, y, upper, lower=upper, length=0.1,...){
if(length(x) != length(y) | length(y) !=length(lower) | length(lower) !=
length(upper))
stop("vectors must be same length")
arrows(x,y+upper, x, y-lower, angle=90, code=3, length=length, ...)
}
stdevs<-aggregate(appxincome~sex,FUN=sd)
lengths<-aggregate(appxincome~sex,FUN=length)
error.bar(boxplot1,averg[,2], 1.96*stdevs[,2]/lengths[,2])
我收到有关矢量长度的错误消息。有人可以帮我解决这个问题吗?感谢
答案 0 :(得分:0)
以下是使用ggplot进行简单ANOVA绘图的方法。
为displ ~ class
数据采用线性模型示例mpg
。
mod <- lm(displ ~ class, data=mpg)
为每个班级建立适合度和置信区间:
newdat <- data.frame(class=levels(as.factor(mpg$class)))
newdat$fit <- predict(mod, newdat)
newdat$SE <- predict(mod, newdat, se.fit=TRUE)[[2]]
newdat$upp <- newdat$fit + 1.96*newdat$SE
newdat$lwr <- newdat$fit - 1.96*newdat$SE
newdat
class fit SE upp lwr
1 2seater 6.160000 0.3822334 6.909177 5.410823
2 compact 2.325532 0.1246708 2.569887 2.081177
3 midsize 2.921951 0.1334817 3.183575 2.660327
4 minivan 3.390909 0.2577017 3.896004 2.885814
5 pickup 4.418182 0.1487842 4.709799 4.126565
6 subcompact 2.660000 0.1444707 2.943162 2.376838
7 suv 4.456452 0.1085470 4.669204 4.243700
使用ggplot绘制条形图和错误栏:
library(ggplot2)
ggplot(newdat, aes(x=class, y=fit)) +
geom_bar(stat="identity") +
geom_errorbar(aes(ymin=lwr, ymax=upp))