[英]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.