在R中绘制最佳拟合直线

5

现在我有一个大的数据集,其中温度一直在上下波动。

我想平滑我的数据,并绘制所有温度的最佳拟合线。

以下是数据:

weather.data  
    date        mtemp   
1   2008-01-01  12.9        
2   2008-01-02  12.9        
3   2008-01-03  14.5        
4   2008-01-04  15.7            
5   2008-01-05  17.0        
6   2008-01-06  17.8    
7   2008-01-07  20.2        
8   2008-01-08  20.8        
9   2008-01-09  21.4        
10  2008-01-10  20.8        
11  2008-01-11  21.4        
12  2008-01-12  22.0        

直至2009年12月31日,等等......

我目前的图表如下所示,我的数据符合运行平均或loess回归的曲线:

enter image description here

然而,当我试图用运行平均来拟合它时,它变成了这个样子:

enter image description here

以下是我的代码。

plot(weather.data$date,weather.data$mtemp,ylim=c(0,30),type='l',col="orange")
par(new=TRUE)

有人可以帮我一下吗?

(内容涉及IT技术)

你需要更具体一些。你想如何平滑你的数据?移动平均、指数平滑还是其他什么方法? - Anders Ellern Bilgrau
1个回答

15

基于你的实际数据以及你想要如何平滑它,以及为什么要进行平滑处理,有许多不同的选项。

我将使用线性回归(一阶和二阶)和局部回归(LOESS)作为例子。但这些可能不是适合你的数据的最佳统计模型,毕竟没有看到数据很难判断。无论如何:

time <- 0:100
temp <- 20+ 0.01 * time^2 + 0.8 * time + rnorm(101, 0, 5)

# Generate first order linear model
lin.mod <- lm(temp~time)

# Generate second order linear model
lin.mod2 <- lm(temp~I(time^2)+time)

# Calculate local regression
ls <- loess(temp~time)

# Predict the data (passing only the model runs the prediction 
# on the data points used to generate the model itself)
pr.lm <- predict(lin.mod)
pr.lm2 <- predict(lin.mod2)
pr.loess <- predict(ls)

par(mfrow=c(2,2))
plot(time, temp, "l", las=1, xlab="Time", ylab="Temperature")
lines(pr.lm~time, col="blue", lwd=2)

plot(time, temp, "l", las=1, xlab="Time", ylab="Temperature")
lines(pr.lm2~time, col="green", lwd=2)

plot(time, temp, "l", las=1, xlab="Time", ylab="Temperature")
lines(pr.loess~time, col="red", lwd=2)

另一种选择是使用移动平均值。

例如:

library(zoo)
mov.avg <- rollmean(temp, 5, fill=NA)
plot(time, temp, "l")
lines(time, mov.avg, col="orange", lwd=2)

平滑处理示例


- londwwq1
我的当前图表看起来像这样,我的数据适合回归,如移动平均线或loess。 - londwwq1
然而,当我尝试将其与移动平均拟合时,它变成了这样...... http://i.stack.imgur.com/d9LMc.png - londwwq1
是因为我有实际的日期和时间吗? - londwwq1
@londwwq1:loess 的帮助页面(可使用 ?loess 访问)详细描述了这一点。本质上,它是用于平滑的参数。 - nico
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接