gpt4 book ai didi

r - 控制R中栅格值的图例和颜色?

转载 作者:行者123 更新时间:2023-12-03 18:23:22 24 4
gpt4 key购买 nike

我正在尝试将 ESRI Grid 绘制为表面的光栅图像。我已经想出了如何制作情节,但不知道如何控制 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 值使颜色轴超出了对我有用的范围。见下文:

enter image description here

基本上,我想告诉 R 将颜色轴从 25-45 拉伸(stretch),而不是 0-50。我知道在 Matlab 中我会使用命令 caxis . R有类似的东西吗?

最佳答案

我使用数据集“volcano”来生成栅格对象,并使代码可重现。

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

enter image description here

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")

enter image description here

关于r - 控制R中栅格值的图例和颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15813101/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com