【问题标题】:Plot multiple regression lines on one plot in ggplot2在 ggplot2 的一个图上绘制多条回归线
【发布时间】:2021-08-17 17:03:51
【问题描述】:

对不起,如果这是一个重复的问题,但我还没有找到答案,因为我的数据框必须被拆分。我试图在一个图上绘制两条回归线,一条回归线用于时期 1(1815-1899)的数据,一条回归线用于时期 2(1900-2013)的数据。我已经使用dplyr 来拆分数据以运行两个单独的回归,但无法弄清楚如何将它们放在同一个图表上,因为您似乎需要ggplot() 命令中的数据框来绘制线条.有人可以帮忙吗?

谢谢。


library(tidyverse)

brest<-read.csv("brest.csv",header=TRUE) ## read in csv

brest<- na.omit(brest) ## get rid of NAs


brestp1<- select(filter(brest, period == 1),c(year,slr,period)) ## Divide into periods

brestp2<- select(filter(brest, period == 2),c(year,slr,period))

fit1 <- lm(slr ~ year, data = brestp1) ## Run lms
summary(fit1)

fit2<- lm(slr ~ year, data = brestp2)
summary(fit2)

## plot graph
ggplot(brestp1, aes(x = year, y = slr)) +  ### Need not only brestp1 but also brestp2
  geom_point() +
  stat_smooth(method = "lm",se=FALSE)+
  theme_classic()


## Data

## Brest period 1

structure(list(year = 1815:1820, slr = c(6926L, 6959L, 6945L, 
6965L, 6941L, 6909L), period = c(1L, 1L, 1L, 1L, 1L, 1L)), na.action = structure(c(`30` = 30L, 
`31` = 31L, `32` = 32L, `33` = 33L, `34` = 34L, `35` = 35L, `36` = 36L, 
`37` = 37L, `38` = 38L, `39` = 39L, `51` = 51L, `52` = 52L, `53` = 53L, 
`54` = 54L, `138` = 138L, `139` = 139L, `140` = 140L, `141` = 141L, 
`142` = 142L, `143` = 143L, `144` = 144L, `145` = 145L, `146` = 146L
), class = "omit"), row.names = c(NA, 6L), class = "data.frame")

##Brest period 2

structure(list(year = 1900:1905, slr = c(6936L, 6916L, 6923L, 
6976L, 6931L, 6913L), period = c(2L, 2L, 2L, 2L, 2L, 2L)), na.action = structure(c(`30` = 30L, 
`31` = 31L, `32` = 32L, `33` = 33L, `34` = 34L, `35` = 35L, `36` = 36L, 
`37` = 37L, `38` = 38L, `39` = 39L, `51` = 51L, `52` = 52L, `53` = 53L, 
`54` = 54L, `138` = 138L, `139` = 139L, `140` = 140L, `141` = 141L, 
`142` = 142L, `143` = 143L, `144` = 144L, `145` = 145L, `146` = 146L
), class = "omit"), row.names = c(NA, 6L), class = "data.frame")

【问题讨论】:

    标签: r ggplot2 linear-regression lm


    【解决方案1】:

    geom_smooth 与单独的数据一起使用:

    ggplot() +
      geom_smooth(aes(x = year, y = slr), data = brest1, 
                  method = "lm", se = FALSE, color = "red") + 
      geom_smooth(aes(x = year, y = slr), data = brest2, 
                  method = "lm", se = FALSE, color = "blue") + 
      geom_point(aes(x = year, y = slr), data = brest1, color = "red") + 
      geom_point(aes(x = year, y = slr), data = brest2, color = "blue")
    

    【讨论】:

    • 太好了,非常感谢,这就是我想要的。
    猜你喜欢
    • 2017-07-02
    • 1970-01-01
    • 2016-01-31
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多