ggplot2:每个类别一个回归线

时间:2018-06-09 18:08:39

标签: r ggplot2 regression

根据this ggplot2 tutorial,以下代码生成一个多色散点图:

library(ggplot2)
gg <- ggplot(midwest, aes(x=area, y=poptotal)) + 
  geom_point(aes(col=state), size=3) +  # Set color to vary based on state categories.
  geom_smooth(method="lm", col="firebrick", size=2) + 
  coord_cartesian(xlim=c(0, 0.1), ylim=c(0, 1000000)) + 
  labs(title="Area Vs Population", subtitle="From midwest dataset", y="Population", x="Area", caption="Midwest Demographics")
plot(gg)

enter image description here

如何制作多条回归线(即每个状态一条)?

1 个答案:

答案 0 :(得分:2)

实际上,您已将col=state属性移至aes geom_point,这就是geom_smooth无法使用{分组}的原因。一种选择是在col=state aes中移动ggplot。修改后的代码如下:

library(ggplot2)

gg <- ggplot(midwest, aes(x=area, y=poptotal, col=state)) + 
  geom_point(size=3) +  # Set color to vary based on state categories.
  geom_smooth(method="lm", size=1, se=FALSE) + 
  coord_cartesian(xlim=c(0, 0.1), ylim=c(0, 1000000)) + 
  labs(title="Area Vs Population", subtitle="From midwest dataset", y="Population",
  x="Area", caption="Midwest Demographics")
plot(gg)

enter image description here