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

R-如何使用qplot/ggplot2对多个矩阵进行直方图化,r,ggplot2,dataframe,R,Ggplot2,Dataframe,我使用R从NetCDF文件(ncdf4)读取和绘制数据。我最近才开始使用R,所以我很困惑,请原谅 假设我从这些文件中获得了N个二维数值矩阵,每个矩阵都有不同的维数和许多NA值 我必须在同一个图中对这些值进行柱状图,具有给定宽度和给定限制的箱子,每个矩阵都是相同的。 对于一个矩阵,我可以这样做: library(ncdf4) library(ggplot2) file0 <- nc_open("test.nc") #Read a variable prec0 <- ncvar_get

我使用R从NetCDF文件(ncdf4)读取和绘制数据。我最近才开始使用R,所以我很困惑,请原谅

假设我从这些文件中获得了N个二维数值矩阵,每个矩阵都有不同的维数和许多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)
库(ncdf4)
图书馆(GG2)

file0老实说,不清楚您在追求什么(散点图或以值为点的数据直方图?)

这里有几个使用ggplot的例子,可能符合您的目标(基于您的最后一句话:“Y上有密度,X上有垃圾箱”):

#一些数据

nsampleI将从每个光栅提取值,并将其放入data.frame中,每列一个光栅。我会融化这个data.frame并使用
color=variable
绘制结果。您的示例图表明您正在寻找散点图而不是直方图。罗曼鲁什特里克:是的,这是我想到的第一件事,下面的答案中或多或少地解释得很清楚。第一件事正是我要找的,我的好先生,谢谢!我唯一不明白的是该因子()的用法。在我的例子中,它只是返回一个错误:
$@AdrianoFantini中的错误
factor
调用只是为了使我的分类变量成为一个factor(否则,绘图中的图例是一个渐变色条)。从你所写的,我说不出你为什么会出错。你需要做的是有一列密度,一个中点和一个分类不同的组(“你的问题中的多个矩阵”)。如果分类是一个字符向量,
因子
调用是不需要的。@AdrianoFantini同样,请随意投票,或者接受你认为有用的答案。谢谢你的解释。我也不理解这个错误,但它是有效的,因为我只使用字符向量作为分类,所以现在我不会深入挖掘。我接受了答案,但无法投票,因为这是我第一次参加SO,而且我还没有足够的代表性。再次感谢。
# 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)
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)