简体   繁体   中英

R overlay multiple plots in a loop

So I've created a loop that makes 10 individual plots:

for (k in 1:nrow(sites)) {
  temp_title <- paste("site",k, "county", sites[k,2],"site",sites[k,3])
  l <- which(hourly_nj_table$County.Code==sites[k,2]&hourly_nj_table$Site.Num==sites[k,3])#grab data for each site individually
  temp_filename <- paste("/filepath",temp_title,".pdf")
  PM_site <- hourly_nj_table[l,]
  PM_site$realTime <- as.numeric(PM_site$Time.Local)
  PM_mean_site <- aggregate(PM_site, by=list(PM_site$Time.Local),FUN="mean",na.rm=TRUE)   
  plot(PM_mean_site$realTime,PM_mean_site$Sample.Measurement, type="l",lwd=10,main=paste(temp_title),xlab="LocalTime",ylab="Ozone (ppm)")#,ylim=c(0,0.05))
}

But I would like to see how they compare on the same axis. Normally (if i'm just hardcoding it) I would add a new parameter and then create the next plot, but i'm unsure how to incorporate that into a loop.

The data all comes from one csv file if that helps..

Thanks!

You're really very close. Plot() gets the ball rolling, lines() will allow you to draw inside the plot:

for (k in 1:nrow(sites)) {
  temp_title <- paste("site",k, "county", sites[k,2],"site",sites[k,3])
  l <- which(hourly_nj_table$County.Code==sites[k,2]&hourly_nj_table$Site.Num==sites[k,3])#grab data for each site individually
  temp_filename <- paste("/Users/bob111higgins/Documents/School/College/Rutgers/Atmospheric Research",temp_title,".pdf")
  PM_site <- hourly_nj_table[l,]
  PM_site$realTime <- as.numeric(PM_site$Time.Local)
  PM_mean_site <- aggregate(PM_site, by=list(PM_site$Time.Local),FUN="mean",na.rm=TRUE)  #Make it average by time of day so can make time series plots. 
  ifesle(k ==1 , 
  plot(PM_mean_site$realTime,PM_mean_site$Sample.Measurement, type="l",lwd=10,main=paste(temp_title),xlab="LocalTime",ylab="Ozone (ppm)")#,ylim=c(0,0.05)),
  lines(PM_mean_site$realTime,PM_mean_site$Sample.Measurement, lwd=10))
}

I'm sure there are better ways to go about this, but this is how I've done it in the past.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM