【发布时间】:2014-10-09 08:26:55
【问题描述】:
我正在使用 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)
但是我发现最好使用 DataFrame 来绘制多个矩阵。我不确定这一点,也不知道该怎么做。这也将允许自动图例以及使用带有 ggplot2 的数据框所带来的所有优势。
我想要实现的目标类似于: https://copy.com/thumbs_public/j86WLyOWRs4N1VTi/scatter_histo.jpg?size=1024
在 Y 上我们有 Density,在 X 上是 bin。
提前致谢。
【问题讨论】:
-
我会从每个栅格中提取值并将它们放入 data.frame 中,每列一个栅格。我会融化这个data.frame并使用
color = variable绘制结果。 -
您的示例图表明您正在寻找散点图而不是直方图。 docs.ggplot2.org/0.9.3.1/geom_point.html 应该可以帮助您到达那里。
-
@RomanLuštrik:是的,这是我想到的第一件事,fileunderwater 在下面的答案中或多或少地解释了。