我想获得单个回归线和相关系数而不是多个回归线。我的代码如下所示。
d1 <- structure(list(x1 = c(50.42,62.59,42.53,55.38,65.23,66.17,47.20,29.40,46.22,65.91), y1 = c(7.00,7.50,4.50,7.58,4.00,4.67,3.50,3.00,3.50,4.63)), .Names = c("x1", "y1"), class = "data.frame", row.names = c(NA,-10L))
d2 <- structure(list(x2 = c(33.65,39.16,46.93,35.75,34.50,31.16,44.72,28.63,42.73,40.54,32.14,33.56), y2 = c(3.00,4.00,3.80,2.76,3.54,3.13,3.50,2.92,4.18,4.22,3.23,2.56)), .Names = c("x2", "y2"), class = "data.frame", row.names = c(NA, -12L))
library(reshape2)
library(ggplot2)
names(d2) <- c("x1", "y2")
df <- rbind(melt(d1, id.vars = "x1"), melt(d2, id.vars = "x1"))
p1 <-ggplot(df, aes(x1, y = value, colour = variable)) +
geom_point(size=4) +
theme(axis.text=element_text(size=16),
axis.title=element_text(size=18,face="bold"), plot.title=element_text(size=32,face="bold"),
legend.text=element_text(size=16),
legend.justification=c(0,1),legend.position=c(0,1),legend.title=element_blank()
) + theme(legend.background = element_rect(
size=0.5, linetype="solid",
colour ="black"), panel.border = element_rect(color="black", size=1, linetype="solid")) + theme(aspect.ratio=1) +
labs(x = "x axis", y = "y axis") +
xlim(0,100) +
ylim(0,10) + geom_smooth(method=lm, se=FALSE, linetype="solid", fullrange=TRUE) + ggtitle("My first plot") +
scale_colour_manual(values = c("green","red"), labels = c("d1", "d2"))
有没有简单的方法可以做到这一点?
答案 0 :(得分:2)
geom_smooth
在color="black"
之外添加aes
(或您想要的任何颜色)。这将覆盖调用ggplot
时指定的颜色美学,并生成单个回归线。
geom_smooth(color="black", method="lm", se=FALSE, linetype="solid", fullrange=TRUE) +
关于您对注释的评论:d1
和d2
不存在于df
数据框中。试试这个:
annotate(x=20, y=5, label=paste("R = ", round(cor(df$x1, df$value),2)), geom="text", size=4)