Plot NetCDF variable-grid data file using ggplot2: “Vector is too large” error

点点圈 提交于 2019-12-03 21:53:41

I remember having a similar problem as you.

Here is what I learned:

As far as I know, ggplot's geom_raster will only plot on a regularly spaced grid, and if you are pulling the unprojected latitudes and longitudes from the raster, you may not have a regularly spaced grid to plot. If you are set on using ggplot to plot your data and you only have the latitudes and longitudes, you will have to find the projection information and project it to its native, regularly spaced grid prior to plotting. ggplot uses projections provided by the mapproject package and does not use PROJ4 projection libraries, which I find to be more powerful and universally supported across other spatial packages in R.

If you are working with a regular grid, which I assume you are, I suggest using the raster package, which can directly read netcdf4 files. For a simple plot, try:

library(raster)
r <- raster("your_nc_file_path", varname = "pr")
plot(r)
contour(r, add = TRUE)

If you have a properly made netcdf file, you can also extract the projection information as well with proj4string(r) or crs(r) or projection(r). You may be able to translate this to work with ggplot's projection system.

Also, if you really, really want to plot this in ggplot, try using the rasterVis package, which conveniently prepares rasters to be used with ggplot.

library(rasterVis)
# Notice `g`plot (from rasterVis) and not `gg`plot
gplot(r) + 
  geom_tile(aes(fill = value))

Hope that helps.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!