我想绘制一些数据,然后为平均值和平均值+/-标准差添加回归线和水平线,每个都有不同的颜色。我已经设法做到了这一点,但我无法正确传说。它显示前两个标签,但没有说明三条水平线。如何让图例也为这三行中的每一行添加标签?
另一篇文章提到show_guide = TRUE,但这对我没有用。我也一直在查看scale_colour_manual的文档,但这对我没有帮助。
我的代码是:
p <- qplot(mpg, wt, data = mtcars, colour="1")
p <- p + geom_smooth(method='lm',aes(x=mpg,y=wt,colour="2"),formula=y~x)
p <- p + geom_hline(yintercept = mean(mtcars$wt), colour = "3")
p <- p + geom_hline(yintercept = mean(mtcars$wt) + sd(mtcars$wt), colour = "3", linetype="dashed")
p <- p + geom_hline(yintercept = mean(mtcars$wt) - sd(mtcars$wt), colour = "3", linetype="dashed")
p <- p + labs(colour="")
p <- p + scale_colour_manual(values = c("red","blue", "green","green","green"),labels=c("Data","Regression","Mean","Mean + SD","Mean - SD"))
p <- p + guides(colour = guide_legend())
print(p)
任何帮助将不胜感激, 干杯!
答案 0 :(得分:2)
我认为这可能更接近你想要的东西:
d <- data.frame(yint = c(mean(mtcars$wt) - sd(mtcars$wt),
mean(mtcars$wt),
mean(mtcars$wt) + sd(mtcars$wt)),
grp = c('dashed','solid','dashed'))
p <- ggplot(data = mtcars,aes(mpg, wt)) +
geom_point(aes(color = "Data")) +
geom_smooth(method='lm',aes(x=mpg,y=wt,color = "Regression"),formula=y~x) +
geom_hline(data = d,aes(yintercept = yint,linetype = grp,color = "Mean +/- SD")) +
scale_linetype_manual(values = c('dashed' = 'dashed','solid' = 'solid')) +
labs(color = "")
print(p)
关于分别标记每条水平线的问题,我的答案是它根本不属于传说。这些应标有geom_text()
:
d <- data.frame(yint = c(mean(mtcars$wt) - sd(mtcars$wt),
mean(mtcars$wt),
mean(mtcars$wt) + sd(mtcars$wt)),
grp = c('dashed','solid','dashed'),
lab = c('-SD','Mean','+SD'))
p <- ggplot(data = mtcars,aes(mpg, wt)) +
geom_point(aes(color = "Data")) +
geom_smooth(method='lm',aes(x=mpg,y=wt,color = "Regression"),formula=y~x) +
geom_hline(data = d,aes(yintercept = yint,linetype = grp),color = "green") +
geom_text(data = d,aes(y = yint,label = lab),
vjust = -0.5,hjust = 1,x = Inf,size = 3) +
scale_linetype_manual(values = c('dashed' = 'dashed','solid' = 'solid')) +
labs(color = "")
print(p)
答案 1 :(得分:-1)
Joran的回答激发了我做出一些改变,现在我已经设法写了一些代码,给了我正在寻找的情节和传奇:
n <- ncol(mtcars)
mtcars[,n+1] <- mean(mtcars$wt)
mtcars[,n+2] <- mean(mtcars$wt) + sd(mtcars$wt)
mtcars[,n+3] <- mean(mtcars$wt) - sd(mtcars$wt)
p <- qplot(mpg,wt,data = mtcars, colour="1")
p <- p + geom_smooth(method='lm',aes(x=mpg,y=wt,colour="2"),formula=y~x)
p <- p + geom_line(aes(x=mpg,y=mtcars[,n+1],colour="3"))
p <- p + geom_line(aes(x=mpg,y=mtcars[,n+2],colour="4"),linetype="dashed")
p <- p + geom_line(aes(x=mpg,y=mtcars[,n+3],colour="5"),linetype="dashed")
p <- p + labs(colour="")
p <- p + scale_colour_manual(values = c("red","blue", "green","green","green"),labels=c("Data","Regression","Mean","Mean + SD","Mean - SD"))
p <- p + guides(colour = guide_legend())
print(p)