【发布时间】:2021-12-25 13:23:51
【问题描述】:
我一直在尝试在 R 中处理这段代码,但遇到了一些困难。我当前的问题是我正在使用的回归代码没有显示出来。这是因为 x 轴是字符而不是数字或日期吗?提前感谢您的帮助!
library(dataRetrieval)
library(plyr)
library(tidyverse)
library(ggpmisc) # for dealing with stat equations
library(ggplot2) # for making plots
library(lubridate) # for working with dates
library(scales) #for working with date_format
library(tidyverse)
library(tibble)
library(tidyr)
siteNo <- "02197000"
pCode <- "00060"
daily <- readNWISdv(siteNo, pCode, "1900-01-01","2021-09-30", statCd="00003")
daily <- renameNWISColumns(daily)
Date <- format(as.Date(daily$Date), format = "%Y-%m-%d")
Date2=format(as.Date(daily$Date), format = "%Y")
#mean_Flow=format(as.integer())
daily2 = ddply(daily, .(site_no, Date2), summarise,
mean_Flow = mean(Flow)*(0.0283168))
#check to see if this date is in the data
for (i in 1900:2021){
#test code to see if its there
print(any(daily2 == i))
#add the year if it doesnt exist
if(any(daily2 == i) == FALSE){
print(i)
print("need to add the")
#how do i add a row for the i
daily2[nrow(daily2) + 1,] = list(siteNo, i,NA)}}
#add the data frame to the new one
lm_eqn <- function(daily2){
m <- lm(mean_Flow ~ Date2, daily2);
eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,
list(a = format(unname(coef(m)[1]), digits = 2),
b = format(unname(coef(m)[2]), digits = 2),
r2 = format(summary(m)$r.squared, digits = 3)))
as.character(as.expression(eq));
}
p1 = ggplot(daily2,aes(Date2,mean_Flow)) +
geom_line(group = 1) +
geom_smooth(method = "lm", se=FALSE, color="black", formula = mean_Flow ~ Date2) +
geom_text(x = 1950, y = 700, label = lm_eqn(daily2), parse = TRUE) +
theme_classic()+
labs(x="", y=(expression(Discharge~(m^{3}~s^{-1}))))+
scale_y_continuous(limits = c(0,800))+
# scale_x_continuous(limits = c(1900,2021),
# breaks = 5)+
theme(axis.text.x = element_text(angle = 45, hjust = 1))
p1
【问题讨论】:
标签: r ggplot2 regression data-retrieval