r - 如何绘制上下平滑线
问题描述
我有一个 ts 图,其中有两条黄土线(跨度不同)。
现在我需要选择其中一条黄土线并平滑残差。在此混凝土上下平滑。它最终应该是这样的:
我的第一个想法真的很愚蠢。我只需要更改跨度值,但这当然是完全错误的。
我无法在 Google 上找到可以帮助我的东西。我的意思是我找到了上平滑和下平滑,但只有计算。是否存在 R 命令可以轻松绘制这些平滑线?
我制作了小桌子以使其更易于运行(不是最好的,但它有效):
table <- structure(list(
Months = c("1980-06", "1980-07", "1980-08", "1980-09",
"1980-10", "1980-11", "1980-12", "1981-01"),
Total = c(75000, 70000, 60000, 73000, 72000, 71000, 76000, 71000)),
.Names = c("Monts", "Total of Killed Pigs"),
row.names = c(NA, 4L), class = "data.frame")
ts.obj <- ts(table$`Total of Killed Pigs`, start = c(1980, 1), frequency = 2)
plot(ts.obj)
trend1 <- loess(ts.obj ~ as.numeric(time(ts.obj)), data = table, span =1)
predict1 <- predict(trend1)
matlines(as.numeric(time(ts.obj)), predict1, col ="blue")
为了完整起见,这里是我的原始代码(我从这个页面得到的表格:https ://datamarket.com/data/set/22ky/monthly-total-number-of-pigs-slaughtered-in-victoria-jan-1980 -august-1995#!ds=22ky&display=line):
obj <- read.csv(file="PATH/monthly-total-number-of-pigs-sla.csv", header=TRUE, sep=",")
ts.obj <- ts(obj$Monthly.total.number.of.pigs.slaughtered.in.Victoria..Jan.1980...August.1995, start = c(1980, 1), frequency = 12)
plot(ts.obj)
trend1 <- loess (ts.obj ~ as.numeric(time(ts.obj)) , data = obj, span =1)
trend2 <- loess (ts.obj ~ as.numeric(time(ts.obj)) , data = obj, span =0.1)
predict1 <- predict (trend1)
predict2 <- predict (trend2)
matlines(as.numeric(time(ts.obj)), predict1, lty =1, col="blue")
matlines(as.numeric(time(ts.obj)), predict2, col="red")
解决方案
使用 的subset
论点loess
。
设置:
tm <- time(ts.ojb)
trend <- loess(ts.obj ~ tm)
pred <- trend$fitted
resid <- trend$residuals
计算loess
正(负)残差为我们提供了上(下)平滑。所以
indexU <- resid > 0
upper <- loess(resid ~ t, subset = indexU)$fitted
绘图时,不要忘记添加偏移量,即trend[indexU]+upper
.
推荐阅读
- d3.js - 通过脚本标签在 JavaScript 模块中导入 D3
- php - 如何使用 PostbackURL 在 html 表格中显示值
- youtube - Youtube apirelatedToVideoId 给出的视频数量不正确
- html - 如何调整选择选项文本?
- android - ReorderableListView : 多个小部件使用相同的 GlobalKey
- python - 在 Selenium 中获取文件选择器对话框的 ID 或其他句柄
- wolkenkit - Wolkenkit 服务的可扩展性
- python - 如何将我的 Rest Api 服务器与我的 Web Socket 服务器通信
- visual-studio-2017 - 如何将 QT5 中的 *.dll 添加/链接到 Visual Studio 2017
- c# - 从数组属性中分配随机文本框