我正在循环使用ggplot创建一些箱形图,并在其中添加线性回归线。效果很好,但是我尝试修改循环以计算每个线性回归的斜率,然后将其输入到不同的df中,但是没有运气
“ y” i包含每个点的值,并且 “ df” i是具有“ y” i值和6个不同周期的数据帧
结果是这样的49张图,基本上我很难找到一种方法来计算每个图的斜率并将它们全部输入到不同的df
for (i in 1:49) {
name1<-paste0("y",i,sep="")
name2<-paste0("df",i,sep="")
mypath<-file.path(path[i])
jpeg(file = mypath,width = 1800, height = 600)
print(ggplot(data=get(name2), aes(x=Periods, y=get(name1))) +
geom_bar(stat="identity", width=0.5,fill="steelblue") +
geom_smooth(aes(x = Periods, y = get(name1), group=1),
method = "lm", se= FALSE, color = "firebrick", size = 2)+
labs(x = "Time Periods") +
labs(y="Number of tropical nights") +
ylim(0,10)+
ggtitle("Number of tropical nights per time period (Tmin > 20°C)")+ theme(plot.title = element_text(hjust = 0.5)))
dev.off()
}
答案 0 :(得分:1)
根据您现在拥有的内容,以下内容应该可以工作:
#simulate data
df1 <- data.frame(Periods=rnorm(10),y1=rnorm(10))
df2 <- data.frame(Periods=rnorm(10),y2=rnorm(10))
df3 <- data.frame(Periods=rnorm(10),y3=rnorm(10))
# list to store results
results = vector("list",3)
for(i in 1:3) {
name1<-paste0("y",i,sep="")
name2<-paste0("df",i,sep="")
FORMULA = as.formula(paste(name1,"~ Periods"))
COEF = as.numeric(coefficients(lm(FORMULA,data=get(name2))))
results[[i]] <- data.frame(
name1=name1,
name2=name2,
intercept=COEF[1],
coefficient=COEF[2]
)
}
do.call(rbind,results)
仍然有50个df浮动有点混乱吗?为什么不尝试这样的事情:
# do not split your dfs, or just combine them like this
DF <-data.frame(
Periods=rnorm(30),y=rnorm(30),
df=paste("df",rep(1:3,each=10),sep="")
)
library(lme4)
coefficients(lmList(y ~ Periods | df,data=DF))
(Intercept) Periods
df1 0.2931990 -0.44942868
df2 0.1146975 0.01613812
df3 -0.3491186 0.11273944
答案 1 :(得分:0)
我尝试了一种替代解决方案,使用下面的代码制作每种情况下的斜率图
x<-0
for (i in 1:6) {
x[i]<-i
}
x<-as.numeric(x)
for (i in 1:49) {
name1<-paste0("y",i,sep="")
name2<-paste0("df",i,sep="")
name4<-paste0("stats",i,sep="")
name5<-paste0("slope",i,sep="")
assign(name4,lm(x~get(name1), data=get(name2)))
assign(name5,get(name4)[[1]][2])
mypath<-file.path(path[i])
jpeg(file = mypath,width = 1800, height = 600)
print(ggplot(data=get(name2), aes(x=Periods, y=get(name1))) +
geom_bar(stat="identity", width=0.5,fill="steelblue") +
annotate("text", x=1.5, y=22, label= get(name5), size=8) +
annotate("text", x=0.75, y=22, label= "Slope=", size=8) +
geom_smooth(aes(x = Periods, y = get(name1), group=1),
method = "lm", se= FALSE, color = "firebrick", size = 2)+
labs(x = "Time Periods") +
labs(y="Number of tropical nights") +
ylim(0,25)+
ggtitle("Number of tropical nights per time period (Tmin > 20°C)")+ theme(plot.title = element_text(hjust = 0.5)))
dev.off()
}