首页 > 解决方案 > 通过 geom_smooth 添加回归线,在一张图中有和没有颜色分组

问题描述

我想说明汇集数据(忽略组)和控制组之间的回归差异。数据来自http://www.jblumenstock.com/files/courses/econ174/FEModels.pdf

paneldata <- data.frame(Location = c("Chicago", "Chicago", "Peoria", "Peoria", "Milwaukee", "Milwaukee", "Madison", "Madison"),
                           Year = rep(2003:2004, 4), 
                           Price = c(75, 85, 50, 48, 60, 65, 55, 60),
                           Quantity = c(2.0, 1.8, 1.0, 1.1, 1.5, 1.4, 0.8, 0.7))

由于geom_smooth自动选择 aes,我可以为所有数据点或组做一条线。但我希望两者都在同一张图中。

library(ggplot2)
library(gridExtra)
plot_pool <- ggplot(paneldata, aes(x=Price, y=Quantity)) + 
  geom_point(aes(colour = Location)) + 
  labs(title="Relationship between Price and Quantity",
       x="Price", y="Quantity") +
  geom_smooth(method = "lm", se = FALSE)  
  
plot_groups <- ggplot(paneldata, aes(x=Price, y=Quantity, colour = Location)) + 
  geom_point() + 
  labs(title="Relationship between Price and Quantity",
       x="Price", y="Quantity") +
  geom_smooth(method = "lm", se = FALSE)  

grid.arrange(plot_pool, plot_groups, ncol=2)

在此处输入图像描述

标签: rggplot2

解决方案


您只需要添加另一个geom_smooth()具有不同美学的:

ggplot(paneldata, aes(x=Price, y=Quantity)) + 
  geom_point() + 
  labs(title="Relationship between Price and Quantity",
       x="Price", y="Quantity") +
  geom_smooth(aes(colour = Location), method = "lm", se = FALSE) +
  geom_smooth(method = "lm", se = FALSE)


推荐阅读