【问题标题】:In ggplot how do I plot the mean line for two groups in a scatterplot在ggplot中,我如何在散点图中绘制两组的平均线
【发布时间】:2021-04-13 02:34:57
【问题描述】:

我想在散点图中显示两组的平均值。我已经对数据进行了排序,因此这些组彼此相邻。第 1 组是前 11 条记录,第 2 组是接下来的 133 条记录。我如何告诉 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

使用geom_smooth(formula = 'y ~ x', se = FALSE, method = "lm") 而不是geom_segment() 可以让我接近我想要的,但我想显示来自lm() 的实际预测值。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    最好只为该层汇总您的数据。例如

    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) 
    

    【讨论】:

      猜你喜欢
      • 2018-06-09
      • 2018-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多