r - 向 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
在该图中添加一条红线?
解决方案
关于修改后的问题,我们进一步修改了那里显示的代码,直接读取URLread.csv
并adjustcolor
从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,但这里是一个使用内置的示例mdeaths
和ldeaths
. 请注意,作为基本包的 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)))
推荐阅读
- line-breaks - “如何修复 MathJax 换行?”
- c++ - 成功注册dll,但在regedit表中没有任何改变
- lua - 如何从 table.remove(x) 中插入 table.insert(x)
- jquery - Azure 图形查询
- oracle - 错误 ORA-06502 WHEN-BUTTON-PRESSED oracle 表单
- spotfire - 当值低于零时,返回零
- android - net.sqlcipher.database.SQLiteException:错误代码 100:另一行可用
- javascript - 提交表单、克隆表单、仅提交新表单、克隆表单等
- html - 如何在不使用 flexbox 的情况下将不同的内容组织在页面的左侧和右侧?
- c++ - C ++ - 分配给'this'不合时宜