【发布时间】:2015-01-01 17:59:45
【问题描述】:
感谢this 的回答,我已经能够使用正确的投影和覆盖图从 NetCDF 文件中绘制地图。 但是,当使用 ggplot 绘制填充的等高线图时,我遇到了一个错误。 (请参阅输入文件的链接答案)
#See https://gis.stackexchange.com/questions/120900/plotting-netcdf-file-using-lat-and-lon-contained-in-variables
# First, estimate the extent.
# We start with the lat and long, then project it to the Lambert Conformal projection
library(raster)
inputfile <- "file.nc"
# Grab the lat and lon from the data
lat <- raster(inputfile, varname="xlat")
lon <- raster(inputfile, varname="xlon")
# Convert to points and match the lat and lons
plat <- rasterToPoints(lat)
plon <- rasterToPoints(lon)
lonlat <- cbind(plon[,3], plat[,3])
# Specify the lonlat as spatial points with projection as long/lat
lonlat <- SpatialPoints(lonlat, proj4string = CRS("+proj=longlat +datum=WGS84"))
# Need the rgdal package to project it to the original coordinate system
library("rgdal")
# My best guess at the proj4 string from the information given
mycrs <- CRS("+proj=lcc +lat_1=35.00 +lat_2=51.00 +lat_0=39.00 +lon_0=14.00 +x_0=-6000. +y_0=-6000. +ellps=sphere +a=6371229. +b=6371229. +units=m +no_defs")
plonlat <- spTransform(lonlat, CRSobj = mycrs)
# Take a look
plonlat
extent(plonlat)
# Yay! Now we can properly set the coordinate information for the raster
pr <- raster(inputfile, varname="pr")
# Fix the projection and extent
projection(pr) <- mycrs
extent(pr) <- extent(plonlat)
# Take a look
pr
plot(pr)
# Project to long lat grid
r <- projectRaster(pr, crs=CRS("+proj=longlat +datum=WGS84"))
library(rasterVis)
#Plot with ggplot:
#Add an overlay map
library(maps)
world <-data.frame(map(plot=FALSE)[c("x","y")])
gplot(r*86400) +
geom_tile(aes(fill=value)) +
scale_fill_discrete() +
geom_path(aes(x,y), data=world) +
coord_equal(xlim=c(xmin(r), xmax(r)), ylim=c(ymin(r), ymax(r)))
Error: Continuous value supplied to discrete scale
这是因为我想绘制一个 discrete 等高线图,它具有离散的颜色,而不是连续的色标。当然,如果使用 scale_fill_continuous,它会起作用。
我不能使用fill=factor(value),因为它需要很长时间(和 GB 的内存),然后为我返回数据集中每个不同值的颜色条目。我可以手动创建一些“箱”并修改数据集以适应这些,但我觉得这将是一个更简单的解决方案的解决方法。
我缺少什么简单优雅的解决方案?我不应该使用 geom_tile(或 geom_raster)吗?
编辑: Thsi 是我想要获得的 pdf 示例: https://copy.com/yMDzEt4i1ELMxpca 该图是使用 GrADS 创建的。颜色图例的存在与否并不重要,有时我使用它有时我不使用它。
编辑2:
cut(value) 可以,但如上所述,我想要一个 ggplot 解决方案,另外......
...是它产生的一个例子。我希望标签位于颜色之间,而不是上方,如下所示:
【问题讨论】:
-
地图最终应该是什么样子并不完全清楚。显然,您不想为
value列中的每个唯一值设置颜色(否则您可以使用fill = factor(value))。对我来说,bin 解决方案是最有意义的,它应该是合理的快速 (?cut)。 -
我编辑了这个问题,并带有一个指向示例 pdf 的链接,它或多或少地代表了我想要获得的内容。
cut()确实是一个选择(谢谢!我没有考虑过),但如果没有 ggplot 方法来处理这个问题,我会感到惊讶。 -
也许这就是你要找的东西:stackoverflow.com/a/25328524
-
@OscarPerpiñán,是的,使用
reclassify()似乎是一个不错的选择。在这一点上,我的东西cut()看起来更干净更简单。 @thothal 您的评论使我朝着正确的方向前进,这似乎是使用cut()。你想扩大下面的答案,我会接受吗?如果没有,我会自己写一个完整的答案,或者在 cmets 中完成你的。我仍然需要一种方法来复制我上一个问题编辑的颜色栏,但这可能是另一个问题的材料。 -
@AdrianoFantini 这取决于您使用该功能的对象。
raster方法仅在您使用Raster*对象提供时才会使用。阅读“方法选择和调度:详细信息”部分here。