Hi I am trying to add density lines to multiple histograms created using R. I have managed to get all 18 lines on the last histogram in the series, however, i cannot figure out how to get each line appear on the correct histogram plot. I know in Matlab there is a hold function, is there something similar in R? the following is the code i have used to get mutiple plots and then add all the lines to the final plot: ##find unique column names in table variablenames<-unique(names(variables)) ## define number of unique names Nvariables<-length(variablenames) ##for loop required for labelling of histograms and to tell how many hist to make for(i in 1:Nvariables){ par(mfrow=c(1,1),ask=TRUE) } ##use lapply for dataframes creates hist for each variable and labels corresponding ##important to have this outside of loop lapply(names(variables),function(i)hist(variables[[i]],probability=T,main=paste("Histogram of",i), xlab=paste(i))) for(i in 1:Nvariables){ lines(density(variables[[i]],lwd=2)) } I am pretty sure its a simple explanation, i have just run out of ideas. Thanks gary Watmough PhD Student University of Southamton School of Geography -- View this message in context: http://www.nabble.com/adding-lines-to-multiple-plot-tp18732850p18732850.html Sent from the R help mailing list archive at Nabble.com.
Gary W <g.watmough <at> gmail.com> writes:> > > Hi > > I am trying to add density lines to multiple histograms created using R. I > have managed to get all 18 lines on the last histogram in the series, > however, i cannot figure out how to get each line appear on the correct > histogram plot. I know in Matlab there is a hold function, is there > something similar in R? > > ##find unique column names in table > variablenames<-unique(names(variables)) > ## define number of unique names > Nvariables<-length(variablenames) > for(i in 1:Nvariables){ > par(mfrow=c(1,1),ask=TRUE) > }previous loop is a little weird -- it has exactly the same result as just running the command inside once. Labeling with the numeric values is a bit of a pain. If you don't need them you can just do lapply(variables, function(v) { hist(v,prob=TRUE) lines(density(v),lwd=2) }) If you need the labels you can either do mapply(function(v,i) { hist(v,prob=TRUE,main=paste("Histogram of",i),xlab=i) lines(density(v),lwd=2) }, variables, 1:Nvariables) Or it might be easier to just do the whole thing with a for loop: for (i in 1:Nvariables) { hist(variables[[i]],prob=TRUE,main=paste("Histogram of",i),xlab=i) lines(density(variables[[i]]),lwd=2) } Ben Bolker