R 在ggplot中,如何在散点图中绘制两组的平均线

R 在ggplot中,如何在散点图中绘制两组的平均线,r,ggplot2,R,Ggplot2,我想在散点图中显示两组的平均值。我已对数据进行了排序,以便各组相邻。组1是前11条记录,组2是下一条记录。如何让ggplot在第一组(1-11号房屋)的范围内画一条线,在第二组(12-133号房屋)的范围内画第二条线 以下是我到目前为止的情况: 代码如下: library(tidyverse) library(tidymodels) data(ames) ames <- AmesHousing::make_ames() set.seed(1) split <- initial

我想在散点图中显示两组的平均值。我已对数据进行了排序,以便各组相邻。组1是前11条记录,组2是下一条记录。如何让ggplot在第一组(1-11号房屋)的范围内画一条线,在第二组(12-133号房屋)的范围内画第二条线

以下是我到目前为止的情况:

代码如下:

library(tidyverse)
library(tidymodels)

data(ames)
ames <- AmesHousing::make_ames()

set.seed(1)
split  <- initial_split(ames, prop = 0.95, strata = "Sale_Price")
ames_plot   <- testing(split)

model1 <- lm(Sale_Price ~ Central_Air, data = ames_plot)

p1 <- model1 %>%
  broom::augment() %>%
  arrange(Central_Air) %>% 
  mutate(House = row_number()) %>% 
  ggplot(aes(House, Sale_Price, color = Central_Air)) + 
  geom_point(size = 1, alpha = 0.3) +
  geom_segment(aes(x = 1, y = .fitted, xend = 144, yend =.fitted)) +
  scale_y_continuous(labels = scales::dollar) 
p1
库(tidyverse)
图书馆(tidymodels)
数据(ames)

ames最好只是总结一下该层的数据。比如说

model1 %>%
  broom::augment() %>%
  arrange(Central_Air) %>% 
  mutate(House = row_number()) %>% 
  ggplot(aes(House, Sale_Price, color = Central_Air)) + 
  geom_point(size = 1, alpha=.3) +
  geom_segment(aes(x = first, y = .fitted, xend = last, yend =.fitted), 
    data = function(x) {
      x %>% 
        group_by(Central_Air)  %>% 
        summarize(first=first(House), last=last(House), .fitted=mean(.fitted), .groups="drop_last")
  }) + 
  scale_y_continuous(labels = scales::dollar) 

最好只对该层的数据进行汇总。比如说

model1 %>%
  broom::augment() %>%
  arrange(Central_Air) %>% 
  mutate(House = row_number()) %>% 
  ggplot(aes(House, Sale_Price, color = Central_Air)) + 
  geom_point(size = 1, alpha=.3) +
  geom_segment(aes(x = first, y = .fitted, xend = last, yend =.fitted), 
    data = function(x) {
      x %>% 
        group_by(Central_Air)  %>% 
        summarize(first=first(House), last=last(House), .fitted=mean(.fitted), .groups="drop_last")
  }) + 
  scale_y_continuous(labels = scales::dollar)