首页 > 解决方案 > 向 ts.plot 添加黄土线

问题描述

假设以下代码:

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在该图中添加一条红线?

标签: rplottime-series

解决方案


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

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)

给予:

截屏

老的

您将无法使用这么少点的 loess,但这里是一个使用内置的示例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)))

推荐阅读