【问题标题】:How to plot a polynomial regression line on a time series in R?如何在R中的时间序列上绘制多项式回归线?
【发布时间】:2020-10-19 16:34:57
【问题描述】:

我偶尔在 R 中使用时间序列进行数据分析,但我不熟悉使用 ARIMA 等函数进行绘图。

以下问题源于对美国每日 COVID 病例数以立方计算的评论。确实看起来像这样,我想简单地运行三次回归,其目的是在散点图上绘制多项式曲线。由于这是一个时间序列,我认为使用 lm() 函数是行不通的。

代码如下:

options(repr.plot.width=14, repr.plot.height=10)
 
install.packages('RCurl')
require(repr) # Enables resizing of the plots.
require(RCurl)
require(foreign)
require(tidyverse) # To tip the df from long row of dates to cols (pivot_longer())

# Extracting the number of confirmed cummulative cases by country from the Johns Hopkins website:
 
x = getURL("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv")
corona <- read.csv(textConnection(x))
 
corona = (read_csv(x)
          %>% pivot_longer(cols = -c(`Province/State`, `Country/Region`, Lat, Long),
                           names_to = "date",
                           values_to = "cases")
          %>% select(`Province/State`,`Country/Region`, date, cases)
          %>% mutate(date=as.Date(date,format="%m/%d/%y"))
          %>% drop_na(cases)
          %>% rename(country="Country/Region", provinces="Province/State")
)
 
cc <- (corona
       %>% filter(country %in% c("US"))
)
 
ccw <- (cc
        %>% pivot_wider(names_from="country",values_from="cases")
        %>% filter(US>5)
)

first.der<-diff(ccw$US, lag = 1, differences = 1)

plot(ccw$date[2:length(ccw$date)-1], first.der, 
     pch = 19, cex = 1.2,
     ylab='', 
     xlab='',
     main ='Daily COVID-19 cases in US',
     col="firebrick",
     axes=FALSE,
     cex.main=1.5)
abline(h=0)
abline(v=ccw$date[length(ccw$date)-1], col='gray90')
abline(h=first.der[length(ccw$date)-1], col='firebrick', lty=2, lwd=.5)

at1 <- seq(min(ccw$date), max(ccw$date), by=2);
axis.Date(1, at=at1, format="%b %d", las=2, cex.axis=0.7)
axis(side=2, seq(min(first.der),max(first.der),1000), 
     las=2, cex.axis=1)

【问题讨论】:

    标签: r plot time-series regression


    【解决方案1】:

    对于预期的多项式回归,我们只对索引及其多项式进行回归。对于多项式,我们方便地使用poly 并用lines 绘制拟合值。但是,这些案例似乎遵循四次曲线而不是三次曲线。

    ccw$first.der <- c(NA, diff(ccw$US))  ## better add an NA and integrate in data frame
    ccw$index <- 1:length(ccw$US)
    
    fit3 <- lm(first.der ~ poly(index , 3, raw=TRUE), ccw)  ## cubic
    fit4 <- lm(first.der ~ poly(index , 4, raw=TRUE), ccw)  ## quartic
    
    plot(first.der, main="US covid-19", xaxt="n")
    tck <- c(1, 50, 100, 150)
    axis(1, tck, labels=FALSE)
    mtext(ccw$date[tck], 1, 1, at=tck)
    lines(fit3$fitted.values, col=3, lwd=2)
    lines(fit4$fitted.values, col=2, lwd=2)
    legend("topleft", c("cubic", "quartic"), lwd=2, col=3:2)
    

    【讨论】:

    • 还有,ccw$day &lt;- seq_along(ccw$date)是不是打算去掉ccw$date的时间结构?如果是,为什么有必要?
    • @AntoniParellada 我不明白您的第一条评论的后续问题(您已删除的评论),我按照要求展示了多项式回归,使用适当的方法是 lm()。您的其他问题:我们不能在lm 中使用日期。实际上我们需要的是一个索引列。我更改了代码以使其更加明显。你还没试过代码吗?日期已经存在,只是上传了错误的图片。
    • @AntoniParellada 将tck 调整为轴刻度和刻度标签的子集,以获取整个范围只需使用tck &lt;- 1:length(ccw$US),虽然看起来很混乱,但您可以尝试@987654333 中的las=2 @。 `
    • 您知道如何使用mtext 将日期格式从“2020-01-31”更改为“3 月 31”,如 OP 中的情节所示?
    • @AntoniParellada 您可能想在mtexttext= 参数(第一个参数,查找?mtext)上应用strftime,尝试:mtext(strftime(ccw$date[tck], "%b %d"), 1, 1, at=tck, las=2)
    【解决方案2】:

    我无法下载您的数据,因此我提供了一个使用 mtcars 数据集的示例。您可以使用poly()I() 获得多项式回归:

    set.seed(123)
    
    qubic_model <- lm(mpg ~ hp + I(hp^2) + I(hp^3), data = mtcars)
    min_hp <- min(mtcars$hp)
    max_hp <- max(mtcars$hp)
    grid_hp <- seq(min_hp, max_hp, by = 0.1)
    qubic_model_line <- predict(qubic_model, data.frame(hp = grid_hp, `I(hp^2)` = grid_hp^2, `I(hp^3)` = grid_hp^3))
    
    plot(mtcars$hp, mtcars$mpg, col='red',main='mpg vs hp', xlab='hp', ylab = 'mpg', pch=16)
    lines(grid_hp, qubic_model_line, col='green', lwd = 3, pch=18)
    legend(80, 15, legend=c("Data", "Cubic fit"),
           col=c("red", "green"), pch=c(16,18), cex=0.8)
    

    如果你只是想包含一个趋势的插图,你可以使用局部多项式回归,例如ggplot2使用的LOESS方法。

    【讨论】:

    • 我想知道你为什么决定使用 lm() 函数,而不是 ARIMA 或其他时间序列函数...
    • @AntoniParellada 因为它为多项式回归提供了机制——正是您所要求的
    猜你喜欢
    • 2020-05-08
    • 2014-06-13
    • 2021-11-09
    • 2023-01-17
    • 1970-01-01
    相关资源
    最近更新 更多