2012-09-17 86 views
-2

我想为散点图的主对角线和回归线添加一个图例。如何在散点图中为线条创建图例?

我已经搞到现在:

library(ggplot2) 
df = data.frame(x = 1:10, y = 1:10) 

p <- ggplot(df, aes(x, y)) + 
geom_point(size=1.2) + 
scale_x_continuous(expand=c(0,0)) + 
scale_y_continuous(expand=c(0,0)) + 
geom_smooth(method="lm", se=FALSE, formula=y~x, colour="blue", fill=NA, size=1.2) + 
geom_abline(intercept=0, slope=1, size=1.2, colour="red") + 
geom_text(aes(x=max(df[,1])/1.4, y=max(df[,2])/1.2, label=lm_eqn(df)), colour="blue", parse=TRUE) + 
# doesn't work: scale_colour_manual("Lines", labels=c("Main Diagonal", "Regression"), values=c("red", "blue")) + 
labs(x="X", y="Y") 
+2

是什么'lm_eqn'? – Maiasaura

+3

这个答案真的可以找到一些谷歌搜索。如果您有一点使用ggplot2,这是一个了不起的信息来源[R Cookbook](http://wiki.stdout.org/rcookbook/Graphs/Legends%20(ggplot2)/) –

+0

lm_eqn是一个函数,用于计算回归方程。代码可以在这里找到: http://stackoverflow.com/questions/7549694/ggplot2-adding-regression-line-equation-and-r2-on-graph –

回答

0

我终于可以设法创造的回归和位于右下角和有意义的对角线一个传说:

p <- ggplot(df, aes(x, y)) + 
geom_point(size=1.2) + 
scale_x_continuous(expand=c(0,0)) + 
scale_y_continuous(expand=c(0,0)) + 
geom_abline(aes(colour="red"),intercept=0, slope=1, size=1.2, aes(colour="1"), show_guide=TRUE) + # new code 
geom_smooth(method="lm", se=FALSE, formula=y~x, fill=NA, size=1.2, aes(colour="2"), show_guide=TRUE) + # new code 
scale_colour_manual("Lines", labels=c("Diagonal", "Regression"), values=c("red", "blue")) + 
opts(legend.position = c(0.85, 0.15)) # relative values, must be set individually 
4

使用show_guide=TRUE例如

p <- ggplot(df, aes(x, y)) + 
geom_point(size=1.2) + 
scale_x_continuous(expand=c(0,0)) + 
scale_y_continuous(expand=c(0,0)) + 
geom_smooth(method="lm", se=FALSE, formula=y~x, colour="blue", fill=NA, size=1.2) + 
geom_abline(aes(colour="red"),intercept=0, slope=1, size=1.2,show_guide=TRUE) + 
geom_text(aes(x=max(df[,1])/1.4, y=max(df[,2])/1.2, label="lm_eqn(df)"), colour="blue", parse=TRUE) + 
# doesn't work: scale_colour_manual("Lines", labels=c("Main Diagonal", "Regression"), values=c("red", "blue")) + 
labs(x="X", y="Y") + opts(legend.position = 'left') 

再加上你可以如何使用像+ opts(legend.position = 'left')事情得到它左边移动传说。我建议你看一下由Tyler Rinker而且提供的链接如下:

https://github.com/hadley/ggplot2/wiki/Legend-Attributes

而且不知道什么lm_eqn IA所以在我的代码我有""包围它,所以它会出现,因为它是写..

+1

'opts'现在已被弃用,并被'theme' – Maiasaura

+2

@Matthius Munz作为@Maiasaura说你可能想使用'+主题(legend.position =“left”)'而不是'+ opts(legend.position ='left')' –

相关问题