r-使用ggplot2的多条回归线



我需要在我用ggplot2制作的散点图上创建多条回归线,该散点图有两个值,男性和女性,但我在设置代码时遇到了一些麻烦。我使用以下代码创建了一个散点图,显示了两组数据:

ggplot(LifeSatisfaction, aes(x=Country)) + 
geom_point(aes(y = Life_Satisfaction_Female), color = "palevioletred2") + 
geom_smooth(method = "lm", y = Life_Satisfaction_Female, col = "red") +
geom_point(aes(y = Life_Satisfaction_Male), color="steelblue") +
geom_smooth(method = "lm", y = Life_Satisfaction_Male, col = "blue") +
labs (title = "Life Satisfaction per Country", x = "Country", y = "Life Satisfaction Rating") + ylim(5, 8)

我试着用然而,geom_smooth ()似乎不适用于多个值。感谢您的帮助!

编辑:我只是想说,我对rstudio和编码很陌生,所以请简单地解释一下哈哈

geom_point中,y美学映射到Life_Satisfaction列,因此它从该列获取值。如果你对geom_smooth做同样的事情(把y=Life_Satisfaction_X放在aes()里面(,它应该可以正确地从该列获取数据:

ggplot(LifeSatisfaction, aes(x=Country)) + 
geom_point(aes(y = Life_Satisfaction_Female), color = "palevioletred2") + 
geom_point(aes(y = Life_Satisfaction_Male), color = "steelblue") +
geom_smooth(aes(y = Life_Satisfaction_Female), method = "lm", col = "red") +
geom_smooth(aes(y = Life_Satisfaction_Male), method = "lm", col = "blue") +
labs(title = "Life Satisfaction per Country", x = "Country", y = "Life Satisfaction Rating") +
ylim(5, 8)

最新更新