簡體   English   中英

控制R中的柵格值的圖例和顏色?

[英]Controlling legend and colors for raster values in R?

我正在嘗試將ESRI網格繪制為表面的柵格圖像。 我已經弄清楚了如何繪制圖,但沒有找到如何控制R的色標。

# open necessary libraries
library("raster")
library("rgdal")
library("ncdf")

# goal: select an ESRI Grid ASCII file and plot it as an image.
infile <- file.choose("Results")
r <- raster(infile)

# read in metadata from ESRI output file, split up into relevant variables
info <- read.table(infile, nrows=6) 
NCOLS <- info[1,2]
NROWS <- info[2,2]
XLLCORNER <- info[3,2]
YLLCORNER <- info[4,2]
CELLSIZE <- info[5,2]
NODATA_VALUE <- info[6,2]
XURCORNER <- XLLCORNER+(NCOLS-1)*CELLSIZE
YURCORNER <- YLLCORNER+(NROWS-1)*CELLSIZE

# plot output data - whole model domain
pal <- colorRampPalette(c("purple","blue","cyan","green","yellow","red"))
par(mar = c(5,5,2,4))  # margins for each plot, with room for colorbars
par(pin=c(5,5))  # set size of plots (inches)
par(xaxs="i", yaxs="i")  # set up axes to fit data plotted
plot(r, xlim=c(XLLCORNER, XURCORNER), ylim=c(YLLCORNER, YURCORNER), ylab='UTM Zone 16 N Northing [m]', xlab='UTM Zone 16 N Easting [m]', col = pal(50))

“ infile”的示例如下所示:

NCOLS        262  
NROWS        257  
XLLCORNER     304055.000  
YLLCORNER    4792625.000  
CELLSIZE         10.000  
NODATA_VALUE    -9999.000  
42.4 42.6 42.2 0 42.2 42.8 40.5 40.5 42.5 42.5 42.5 42.9 43.0 ...  
42.5 42.5 42.5 0 0 43.3 42.7 43.0 40.5 42.5 42.5 42.4 41.9 ...  
42.2 42.7 41.9 42.9 0 0 43.7 44.0 42.4 42.5 42.5 43.3 43.2 ...  
42.5 42.5 42.5 42.5 0 0 41.9 40.5 42.4 42.5 42.4 42.4 40.5 ...  
41.9 42.9 40.5 43.3 40.5 0 41.9 42.8 42.4 42.4 42.5 42.5 42.5 ...  
...  

問題在於數據中的0值使色軸超出了對我有用的范圍。 見下文:

在此處輸入圖片說明

基本上,我想告訴R將色軸從25-45拉伸,而不是0-50。 我知道在Matlab中我會使用caxis命令。 R有類似的東西嗎?

我使用數據集“火山”生成一個柵格對象,並使代碼可再現。

Ope選項是離散化類別中的柵格值,然后,您可以控制每個類別中的值的范圍。 以下是兩個示例:

1- 情節

library(raster)
library(RColorBrewer)

r = raster(volcano) #raster object

cuts=c(100,150,160,170,180,190,200) #set breaks
pal <- colorRampPalette(c("white","black"))

plot(r, breaks=cuts, col = pal(7)) #plot with defined breaks

在此處輸入圖片說明

2- ggplot2

library(ggplot2)
library(raster)
library(RColorBrewer)

r = raster(volcano) #raster object
#preparing raster object to plot with geom_tile in ggplot2
r_points = rasterToPoints(r)
r_df = data.frame(r_points)
head(r_df) #breaks will be set to column "layer"
r_df$cuts=cut(r_df$layer,breaks=c(100,150,160,170,180,190,200)) #set breaks

ggplot(data=r_df) + 
  geom_tile(aes(x=x,y=y,fill=cuts)) + 
  scale_fill_brewer("Legend_title",type = "seq", palette = "Greys") +
  coord_equal() +
  theme_bw() +
  theme(panel.grid.major = element_blank()) +
  xlab("Longitude") + ylab("Latitude")

在此處輸入圖片說明

暫無
暫無

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

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