首页 > 解决方案 > 如何绘制上下平滑线

问题描述

我有一个 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")

标签: r

解决方案


使用 的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.


推荐阅读