Adding a loess line to a ts.plot

Viewed 48

Assume the following code:

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')
    

How can I add a red loess line to this plot?

1 Answers

Regarding the modified question, we further modified the code shown there to read the URL directly in read.csv and to use adjustcolor from the base of R and then add the red loess line as shown. No packages are used.

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)

giving:

screenshot

Old

You are not going to be able to use loess with so few points but here is an example using the builtin mdeaths and ldeaths. Note that grDevices, which is a base package, has adjustcolor so you don't need to use ggplot2 to get 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)))
Related