我正在尝试向我的绘图添加线性回归模型。我有这个数据框:
watershed sqm cfs
3 deerfieldwatershed 1718617392 22703.8851
5 greenwatershed 233458430 1637.4895
6 northwatershed 240348182 3281.9921
8 southwatershed 68031782 867.6428
我当前的代码是:
ggplot(dischargevsarea, aes(x = sqm, y = cfs, color = watershed)) +
geom_point(aes(color = watershed), size = 2) +
labs(y= "Discharge (cfs)", x = "Area (sq. m)", color = "Watershed") +
scale_color_manual(values = c("#BAC4C1", "#37B795",
"#00898F", "#002245"),
labels = c("Deerfield", "Green", "North",
"South")) +
theme_minimal() +
geom_smooth(method = "lm", se = FALSE)
运行时会在图例中的点上添加一条线,但不会显示在图形上(请参见下图)。我怀疑它是为每个点分别绘制一条线,但我希望所有四个点都具有一条回归线。如何获得要显示的行?谢谢。
答案 0 :(得分:0)
您是对的,这是因为您的点被分为不同的类别(因为第一个color
中的aes
),所以当您调用geom_smooth
时,它将使每个类别的回归线,在您的示例中,它表示每个点。因此,这就是为什么您没有一条回归线的原因。
要获得所有点的回归线,您只能在color
的{{1}}中传递aes
参数(也可以在{{1 }}指示geom_point
不考虑先前的映射参数,并用新参数填充它)。
要在图表上显示方程式(基于您在注释中的问题),可以使用inherit.aes = FALSE
包中的geom_smooth
函数(此处是描述其用法的SO帖子:{ {3}}):
ggplot
Add regression line equation and R^2 on graph
数据
stat_poly_eq