我正在尝试绘制从孔中采集的样品的折线图,特别是对于四种“化学药品”,然后将每个孔的那四张图堆叠起来并保存为pdf。我没练习过,我很生锈。目前,我的for循环在中间停止,并弹出上述错误。
以下大致是我的数据和我正在调用的包的样子:
ID date chemical result
<chr> <dttm> <chr> <num>
1 MW-01 2020-01-06 10:30:00 chemical 1~ 0.02
9 MW-02 2020-01-06 13:34:00 chemical 2~ 0.02
library(openxlsx)
library(tidyr)
library(ggplot2)
library(doBy)
library(lubridate)
library(officer)
library(readxl)
library(ggrepel)
library(ggridges)
library(cowplot)
library(data.table)
library(scales)
library("plyr")
library(dplyr)
下面是我的for循环,其中没有针对图3-4(为简洁起见)的if语句,这些语句完全按照第一/第二个图插入其他化学物质进行处理。孔列表是一个具有两列的数据框:孔ID和一个生成的图形编号。我注意到我的脚本正在大约20%的井中运行,然后出现错误。
for(l in 1:n_wells){
plot.dat<-data.frame(subset(tableH,(id %like% well_list[l,1])))
stacked.dat<-subset(plot.dat,(chemical %like% c("chemical 1","chemical 2",
"chemical 3","chemical 4")))
well<-well_list[l,1]
#min.date<-as.POSIXct("2020-01-01")
#max.date<-as.POSIXct("2020-07-01")
chm1table_lp <- subset(stacked.dat,(chemical %like% "chemical 1"))
chm2table_lp <- subset(stacked.dat,(chemical %like% "chemical 2"))
chm3table_lp <- subset(stacked.dat,(chemical %like% "chemical 3"))
chm4table_lp <- subset(stacked.dat,(chemical %like% "chemical 4"))
if(nrow(chm1table_lp)>0){
minc1 <- min(chm1table$result)
maxc1 <- max(chm1table$result)
chm1_plot <- ggplot(chm1table_lp, aes(x=sample_date,y=result))+
geom_line(data=chm1table_lp,aes(x=sample_date,y=result,group=1),color="orange",size=1)+
geom_point(data=chm1table_lp,shape=1,color="orange",size=2)+
labs(y="mg/L",x="Date")+
scale_color_discrete("Legend") +
scale_x_datetime(date_labels="%m/%Y",limits=c(min.date,max.date))+
scale_y_continuous(limits=c(minc1,maxc1),
breaks= breaks_extended(n=10))+
ggtitle(well)
plot_list[[k]] <- chm1_plot
k=k+1
}
if(nrow(chm2table_lp)>0){
minc2 <- min(chm2table$result)
maxc2 <- max(chm2table$result)
print("in chm2 if statement, min and max work")
chm2_plot <- ggplot(chm2table_lp, aes(x=sample_date,y=result,group=1))+
geom_line(data=tdstable_lp, aes(x=sample_date,y=result),color="blue",size=1)+
geom_point(data=chm2table_lp,shape=1,color="blue",size=2)+
labs(y="mg/L",x="Date")+
scale_color_discrete("Legend") +
scale_x_datetime(date_labels="%m/%Y",limits=c(min.date,max.date))+
scale_y_continuous(limits=c(minc2,maxc2),
breaks= breaks_extended(n=10))+
ggtitle(well)
print("chm2 plot works")
print(tds_plot)
#adding to plot list
plot_list[[k]] <- chm2_plot
print("chm2 plot added to list")
#increase index by 1
k=k+1
print("index increase after chm2")
}
multi_plot <- plot_grid(plotlist = plot_list,ncol=1,align = "v")
pdfname<-paste(well,".pdf",collapse=NULL,sep="")
ggsave(pdfname)
plot_list <- vector(mode="list")
k=1
}
感谢您的帮助!