Kara Przeczek
2013-Jul-10 19:06 UTC
[R] how to adjust the x axis range based on y axis data
I am using R studio version 0.97.336. I am trying to produce multiple figures based on a large data set (98010 rows). I am creating a plot for each TITLE (related to a variable/station combination). #Create a plot for each Title. Save all plots as jpegs in folder named "SkeenaQfigs" for(i in 1:nlevels(dt$TITLE)){ tmp.title <- subset(dt, TITLE == levels(dt$TITLE)[i]) #save plot to file setwd("H:/R stuff/SJackson/SkeenaQfigs") options(show.error.messages = FALSE) result <- try(plot(tmp.title$YEAR, tmp.title$VALUE, xlab = "Year", ylab="", main = tmp.title$TITLE[1])) if(class(result) == 'try-error') { print(paste("error", tmp.title$TITLE[1], sep=" ")) } else { jpeg(file = paste(tmp.title$TITLE[1],".jpg",sep="")) plot(tmp.title$YEAR, tmp.title$VALUE, xlab = "Year", ylab="", main = tmp.title$TITLE[1]) dev.off() } } The range of YEAR is the same for every station, but there is not always data for every year (and some stations have no data). I would like each plot to adjust the x-axis to start at the first occurrence of a y value. I used tmp.title <- tmp.title[!is.na(tmp.title$VALUE),] to remove all the rows where VALUE = NA. However, there are some years later on in the data set that are missing data, but I want those to be included. I only want to remove the first empty rows. I then tried, xmin <- min(tmp.title$YEAR[tmp.title$VALUE>0], na.rm=T) xmax <- max(tmp.title$YEAR, na.rm=T) plot(tmp.title$YEAR, tmp.title$VALUE, xlab = "Year", ylab="", xlim=c(xmin,xmax), main = tmp.title$TITLE[1]) This works, but is there a simpler way to do this within the plot command? Thank you very much for your help! Kara