簡體   English   中英

用離散色標繪制填充輪廓圖

[英]Plotting filled contour map with discrete color scale

多虧了這個答案,我才能夠使用正確的投影和覆蓋圖繪制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
這是因為我要繪制具有離散顏色而不是連續色標的離散輪廓圖。 當然,如果使用scale_fill_continuous,它就可以工作。
我不能使用fill=factor(value)因為它將花費一定的時間(和GB的內存),然后為數據集中的每個不同值返回一個帶有顏色條目的顏色。 我可以手動創建一些“ bin”並修改數據集以適合其中的那些,但是我覺得這將是一種更簡單的解決方案。

我缺少的簡單優雅的解決方案是什么? 我不應該使用geom_tile(或geom_raster)嗎?

編輯:這是我想要得到的pdf示例: https ://copy.com/yMDzEt4i1ELMxpca該圖是用GrADS創建的。 顏色圖例的存在與否並不重要,有時我會使用,有時則不使用。

EDIT2: cut(value)可以,但是如上所述,我想要一個ggplot解決方案,另外...

...是它產生的一個例子。 我希望標簽位於顏色之間,而不是上方,如下所示:

根據您的修改,我將執行以下操作:

r$value.bin <- cut(r$value, c(0:4, 2 * (3:5)))
gplot(r*86400) + 
    geom_tile(aes(fill = value.bin)) + 
    scale_fill_manual(
       values = colorRampPalette(brewer.pal(9, "Greens"))(nlevels(r$value.bin))) + 
    geom_path(aes(x,y), data=world) + 
    coord_equal(xlim=c(xmin(r), xmax(r)), ylim=c(ymin(r), ymax(r)))

也許您必須使用scale_fill_manual的顏色並進行一些裁剪,以使某些斑點具有NA顏色。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM