根据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)
如何制作多条回归线(即每个状态一条)?
答案 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)