R - 如何使用ggplot / ggplot2对多个矩阵进行直方图化

时间:2014-10-09 08:26:55

标签: r ggplot2 dataframe

我正在使用R来读取和绘制来自NetCDF文件(ncdf4)的数据。我最近才开始使用R,因此我很困惑,请原谅。

假设我从文件中获得了数值的N 2-D矩阵,每个矩阵具有不同的维度和许多NA值。

我必须在同一个图中对这些值进行直方图,给定宽度的区间和给定的限制,每个矩阵都相同。 对于一个矩阵,我可以这样做:

library(ncdf4)
library(ggplot2)

file0 <- nc_open("test.nc")
#Read a 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 the histogram
histo_prec0 <- hist(prec0, xlim=c(min_plot,max_plot), right=FALSE, breaks=seq(0,ceiling(maximum_prec0),by=bin_width))
#Plot the histogram densities using points instead of bars, which is what we 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 to vector using
#vector_prec0 <- c(prec0)

然而,我发现最好使用DataFrame绘制多个矩阵。我不确定这一点,也不确定如何做到这一点。这也可以实现自动图例以及使用ggplot2数据帧所带来的所有优势。

我想要实现的是类似于此的东西: https://copy.com/thumbs_public/j86WLyOWRs4N1VTi/scatter_histo.jpg?size=1024

在Y上我们有密度,在X上有箱子。

提前致谢。

1 个答案:

答案 0 :(得分:2)

老实说,目前还不清楚你的目标是什么(散点图或数据的直方图,数值为点?)。

以下是一些使用ggplot的例子,它们可能符合您的目标(基于您的最后一句:&#34; 在Y上我们有密度,在X上有箱子&#34; ):

# some data 
nsample<- 200
d1<- rnorm(nsample,1,0.5)
d2<- rnorm(nsample,2,0.6)

#transformed into histogram bins and collected in a data 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)

enter image description here

但是,您也可以直接在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))  # for histogram instead
windows()
print(plots2)

enter image description here