[英]How to put the regression equation on a plot of monthly time series data?
我想分析每月降雨数据(绘制时间序列图+时间序列的回归方程式)。 我已经用R语言编写了代码,并绘制了每月的时间序列数据,我试图制作不同的回归方程式(线性和非线性),并在同一时间序列图上显示这些方程式,但是不幸的是我不能。 可能是因为我是R / Rstudio统计软件包的新用户。
资料样式
Date monthly rainfall (mm)
jan94 12
Feb94 11
.
.
. Dec14 1x
编码
# plotting of time series rainfall data (option1)
# step1: read files
MR<-read.table("C:\\Users\\Salam\\Desktop\\trend Kufa\\CSV2 Habel\\Monthly rainfall.csv", header=T,sep=",")
summary(MR)
names(MR)
MR
# step2: plot observed discharge
MR1<-MR[c(1:252),2];
summary (MR1)
MR1
class(MR1)
require(zoo)
x <- yearmon(1994 + seq(0, 251)/12)
x
y<-MR1
y
pcp<-y~x
plot(pcp,type="l", xlab="Month",ylab="Monthly Rainfall(mm)", axes=T)
grid(nx=250, ny=250, col="lightgray", lty="solid")
lines(pcp,lwd=2, col="blue")
box(which='plot')
title("Monthly Observed rainfall(mm)")
## Regression
S1 <- lm(y ~ z, data=MR)
abline(S1,col='red',lwd=3)
summary(S1)
S2<-lm( y~poly(x,3), data=MR)
summary(S2)
abline(S2,col='green',lwd=3)
S3 <- nls(y ~ exp(a + b / x),start = list(a = 0, b = 0))
summary(S3)
S4 <- nls(y ~ (a + b *log( x)), start = list(a = 0, b = 0))
summary(S4)
您可以使用文本函数将方程式放在绘图上。
text(x, y, "S1 <- lm(y ~ z, data=x)",
cex = .8)
x和y是绘图上您希望方程式的坐标
用引号将等式
数据就是你的数据框架
cex控制字体大小
有关文本的更多信息和选项,请使用?text
检查以下示例,您可以轻松地对其进行修改。
library(ggplot2)
# example dataset
dt = data.frame(date = 1:10,
value = c(10,11,15,13,16,17,18,19,16,22))
# plot everything in one graph
ggplot(dt, aes(date, value)) +
geom_point() + # plot the points
stat_smooth(method="lm",se=F,level=0.95, col="red") + # linear reg
stat_smooth(method="lm", formula = y~poly(x,2,raw=T), se=F,level=0.95, col="blue") + # quadratic reg
stat_smooth(method="lm", formula = y~poly(x,3,raw=T), se=F,level=0.95, col="green") # cubic reg
# plot everything in separately
library(gridExtra)
plot1 = ggplot(dt, aes(date, value)) +
geom_point() +
stat_smooth(method="lm",se=T,level=0.95, col="red")
plot2 = ggplot(dt, aes(date, value)) +
geom_point() +
stat_smooth(method="lm", formula = y~poly(x,2,raw=T), se=T,level=0.95, col="blue")
plot3 = ggplot(dt, aes(date, value)) +
geom_point() +
stat_smooth(method="lm", formula = y~poly(x,3,raw=T), se=T,level=0.95, col="green")
grid.arrange(plot1,plot2,plot3)
我希望您熟悉ggplot2软件包,因为在这种情况下它是最重要的。 然后,您可以研究添加标题,更改颜色,更改置信区间等的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.