簡體   English   中英

通過 geom_smooth 添加回歸線,在一張圖中有和沒有顏色分組

[英]Add regression line via geom_smooth with and without colour grouping in one graph

我想說明匯集數據(忽略組)和控制組之間的回歸差異。 數據來自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)

在此處輸入圖像描述

您只需要添加另一個具有不同美學的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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM