I want to save multiple plots to a pdf file. So I tried to use a list to save the results of ggplot. But the problem is the first place of the list is always wrong with that error:
Error: Aesthetics must be either length 1 or the same as the data (651): x, y, colour.
And the rest of the list doesn't have this problem. The code is here:
raw_data <- read.csv("hourly_42401_2018.csv")
raw_data <- separate(data=raw_data,col=Date.Local,into=c("year","month","day"),sep="-")
data <- raw_data[raw_data$State.Name=="Alabama"&raw_data$County.Name=="Jefferson"&raw_data$Site.Num=="23",c("Time.Local","Sample.Measurement","month","day")]
data$Time.Local <- as.numeric(data$Time.Local)-1
m <- c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
num_m <- unique(data$month)
filename=paste("D:/test/temp1","/","SO2",".pdf",sep="")
plot_list <- list()
for(i in 1:length(num_m))
{
data_m <- data[data$month==num_m[i],]
if(nrow(data_m)==0)
next
title <- paste("SO2",",",m[as.numeric(num_m[i])],",",2018,",","Alabama",",","Jefferson",",","23",sep="")
plot_list[[i]] <- ggplot(data_m,aes(x=data_m$Time.Local,y=data_m$Sample.Measurement,colour=data_m$day))+
geom_point()+geom_line()+xlab("Time")+ylab("parts per million")+labs(fill="Day")+ggtitle(title)+
theme(plot.title = element_text(hjust = 0.5))+scale_x_continuous(breaks=seq(0,24,6))
#ggsave(filename,width=50,height=20,units="cm",dpi=300)
}
pdf(filename)
for(i in 1:length(num_m))
{
p <- plot_list[[i]]
print(p)
}
dev.off()
And the list description is here:
enter image description here
Thank very much!
It's my first time to ask for help on this website. I am sorry I forgot the sample input and result I expected.The raw data is here:https://drive.google.com/file/d/1Ny3i_W0H9-w0WjXTPZtdQ6QyKXzdv9Va/view?usp=sharing. The data frame data_m
is the input data:
> head(data_m)
Time.Local Sample.Measurement month day
652 0 0.4 02 01
653 1 0.3 02 01
654 2 0.2 02 01
655 3 0.2 02 01
656 4 0.1 02 01
657 5 0.2 02 01
And the result I am looking for is a pdf file with plots on each page.One of the plots is like that: enter image description here