【问题标题】:Adding a loess line to a ts.plot向 ts.plot 添加黄土线
【发布时间】:2021-10-16 20:10:26
【问题描述】:

假设以下代码:

library(ggplot2)
library(RCurl)
x <- getURL("https://gist.githubusercontent.com/aronlindberg/dfa0115f1d80b84ebd48b3ed52f9c5ac/raw/3abf0f280a948d6273a61a75415796cc103f20e7/growth_data.csv")
data <- read.csv(text = x)
data <- data[,2:20]

data[cbind(FALSE, t(apply(data[,-1], 1, function(z) duplicated(z)
 & z >= max(z))))] <- NA

ts.plot(t(data)+2, gpars = list(col = ggplot2::alpha("black", 0.5),
 ylim = c(0.5, 500), xlim = c(2, 20), xlab = "Years", 
 ylab = "Cumulative Numbers"), log = 'y')
    

如何在该图中添加一条红色的loess 线?

【问题讨论】:

    标签: r plot time-series


    【解决方案1】:

    关于修改后的问题,我们进一步修改了那里显示的代码,直接读取read.csv中的URL,并从R的基础上使用adjustcolor,然后添加如图所示的红色黄土线。没有使用任何包。

    u <- "https://gist.githubusercontent.com/aronlindberg/dfa0115f1d80b84ebd48b3ed52f9c5ac/raw/3abf0f280a948d6273a61a75415796cc103f20e7/growth_data.csv"
    data <- read.csv(u)[, 2:20]
    data[cbind(FALSE, t(apply(data[,-1], 1, function(z) duplicated(z)
     & z >= max(z))))] <- NA
    
    data2 <- data + 2
    
    ts.plot(t(data2), gpars = list(col = adjustcolor("black", 0.5),
     ylim = c(0.5, 500), xlim = c(2, 20), xlab = "Years", 
     ylab = "Cumulative Numbers"), log = 'y')
    
    s <- na.omit(stack(data2))
    s$years <- as.integer(s$ind)
    lo <- loess(values ~ years, s)
    lines(fitted(lo) ~ years, s, col = "red", lwd = 2)
    

    给予:

    你不能用这么少的点来使用黄土,但这里有一个使用内置 mdeathsldeaths 的例子。请注意,作为基础包的 grDevices 具有调整颜色,因此您无需使用 ggplot2 来获取 alpha。

    lo.m <- fitted(loess(mdeaths ~ time(mdeaths)))
    lo.l <- fitted(loess(ldeaths ~ time(ldeaths)))
    
    ts.plot(mdeaths, ldeaths, lo.m, lo.l, 
      gpars = list(col = adjustcolor(1:2, 0.5), lty = c(1, 1, 2, 2)))
    

    【讨论】:

    • @g-grothendieck -- 我已经用更多数据点更新了数据集。我尝试使用与您类似的代码从其他数据集进行翻译,但它似乎从未对我自己的数据起作用...
    • 已修改答案以处理提供的新数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 2012-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多