[英]In ggplot how do I plot the mean line for two groups in a scatterplot
我想在散点图中显示两组的平均值。 我已经对数据进行了排序,因此这些组彼此相邻。 第 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()
的实际预测值。
最好只为该层汇总您的数据。 例如
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.