使用 facet() 在散点图中绘制多条回归线,并将斜率系数添加到每条线

Plot more than one regression line in a scatterplot using facet() and add the slope coefficient to every line

我想在散点图中绘制每个城市的回归线。

数据框看起来像:

     df
            City      str    testscr
19     Los Angeles 22.70402  619.80
31       San Diego 20.60697  624.55
33     Los Angeles 21.53581  625.30
35  San Bernardino 21.19407  626.10
36     Los Angeles 21.86535  626.80
45       Riverside 19.26697  628.75
46     Los Angeles 23.30189  629.80
63          Orange 21.94756  633.15
67     Los Angeles 20.68242  634.05
69       San Diego 21.78650  634.10
72     Los Angeles 21.15289  634.40
76  San Bernardino 18.98373  634.95
86  San Bernardino 19.30676  636.60
87       Riverside 20.89231  636.70
105 San Bernardino 19.75422  639.35
114         Orange 19.62662  640.75
118      San Diego 20.08452  641.45
126      Riverside 22.81818  643.20
128    Los Angeles 21.37363  643.40
146      San Diego 19.79654  645.55
156         Orange 21.04869  646.70
157         Orange 20.17544  646.90
160      San Diego 20.29137  647.25
168      San Diego 17.15328  648.70
169 San Bernardino 22.34977  648.95
170         Orange 22.17007  649.15
191         Orange 23.01438  652.10
200      Riverside 21.03721  653.40

我的方法是:

ggplot(data=df,aes(x=str,y=testscr))+
  geom_point()+
  geom_smooth(method="lm",se=FALSE)+
  facet_grid(. ~City)

有没有更聪明或更好的方法?以及如何将斜率系数添加到每条回归线?

我们先处理组,然后回答第二部分关于添加标签。

如果要按组绘制,基本上有两种选择。首先是分面,就像你一样。第二种是对点进行分组,或者明确地使用 aes(group = City),或者通过另一种审美方式,例如 aes(color = City).

如果第二种方法生成的图很乱,例如有很多重叠线,那么最好使用分面。

几个使用 iris 数据集的示例。

首先,按颜色分组:

library(ggplot2)
iris %>% 
  ggplot(aes(Petal.Length, Sepal.Length)) + 
  geom_point(aes(color = Species)) + 
  geom_smooth(method = "lm", 
              aes(color = Species), 
              se = FALSE)

分组:

iris %>% 
  ggplot(aes(Petal.Length, Sepal.Length)) + 
  geom_point(aes(group = Species)) + 
  geom_smooth(method = "lm", 
              aes(color = Species), 
              se = FALSE)

使用构面:

iris %>% 
  ggplot(aes(Petal.Length, Sepal.Length)) + 
  geom_point() + 
  geom_smooth(method = "lm", 
              se = FALSE) +
  facet_wrap(~Species)

要添加系数等标签,请查看 ggpmisc 包。这是使用 stat_fit_tb 添加系数的一种方法:

iris %>% 
  ggplot(aes(Petal.Length, Sepal.Length)) + 
  geom_point() + 
  geom_smooth(method = "lm", 
              se = FALSE) + 
  facet_wrap(~Species) + 
  stat_fit_tb(method = "lm", 
              tb.type = "fit.coefs")