Monday 15 March 2010

R - How to histogram multiple matrixes using qplot/ggplot2 -



R - How to histogram multiple matrixes using qplot/ggplot2 -

i'm using r read , plot info netcdf files (ncdf4). i've started using r i'm confused, beg pardon.

let's files obtain n 2-d matrixes of numerical values, each different dimensions , many na values.

i have histogram these values in same plot, bins of given width , within given limits, same every matrix. 1 matrix, can this:

library(ncdf4) library(ggplot2) file0 <- nc_open("test.nc") #read variable prec0 <- ncvar_get(file0,"pr") #some settings min_plot=0 max_plot=30 bin_width=2 xlabel="mm/day" ylabel="pdf" title="precipitation" #get maximum of array, exclude nas maximum_prec0=max(prec0, na.rm=true) #store histogram histo_prec0 <- hist(prec0, xlim=c(min_plot,max_plot), right=false, breaks=seq(0,ceiling(maximum_prec0),by=bin_width)) #plot histogram densities using points instead of bars, want qplot(histo_prec0$mids, histo_prec0$density, xlim=c(min_plot,max_plot), color=i("yellow"), xlab=xlabel, ylab=ylabel, main=title, log="y") #if necessary, can transform matrix vector using #vector_prec0 <- c(prec0)

however occurs me best utilize dataframe plotting multiple matrixes. i'm not of nor on how it. allow automatic legends , advantages come using dataframes ggplot2.

what want accomplish akin this: https://copy.com/thumbs_public/j86wlyowrs4n1vti/scatter_histo.jpg?size=1024

where on y have density , on x bins.

thanks in advance.

to honest, unclear after (scatter plot or histogram of info values points?).

here couple of examples using ggplot might fit goals (based on lastly sentence: "where on y have density , on x bins"):

# info nsample<- 200 d1<- rnorm(nsample,1,0.5) d2<- rnorm(nsample,2,0.6) #transformed histogram bins , collected in info frame hist.d1<- hist(d1) hist.d2<- hist(d2) data.d1<- data.frame(hist.d1$mids, hist.d1$density, rep(1,length(hist.d1$density))) data.d2<- data.frame(hist.d2$mids, hist.d2$density, rep(2,length(hist.d2$density))) colnames(data.d1)<- c("bin","den","group") colnames(data.d2)<- c("bin","den","group") ddata<- rbind(data.d1,data.d2) ddata$group<- factor(ddata$group) # plot plots<- ggplot(data=ddata, aes(x=bin, y=den, group=group)) + geom_point(aes(color=group)) + geom_line(aes(color=group)) #optional print(plots)

however, produce smooth density plots (or histograms) straight in ggplot:

ddata2<- cbind(c(rep(1,nsample),rep(2,nsample)),c(d1,d2)) ddata2<- as.data.frame(ddata2) colnames(ddata2)<- c("group","value") ddata2$group<- factor(ddata2$group) plots2<- ggplot(data=ddata2, aes(x=value, group=group)) + geom_density(aes(color=group)) # geom_histogram(aes(color=group, fill=group)) # histogram instead windows() print(plots2)

r ggplot2 data.frame

No comments:

Post a Comment