首页 > 解决方案 > 使用 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和一般编码很陌生,所以请用简单的术语解释一下哈哈

标签: rggplot2

解决方案


geom_point中,y美学被映射到Life_Satisfaction列,因此它从该列获取其值。如果你对geom_smooth(put y=Life_Satisfaction_Xinside 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)

推荐阅读