jju*_*lip 3 plot attributes r raster
我有一个raster
具有大量属性的对象,我想在R中绘制空间数据,并用特定属性对其进行颜色编码.我无法弄清楚如何使用特定属性的信息来实现这一目标.到目前为止,我已经使用成功提取了选择属性factorValues()
,但我无法确定如何将此信息合并到plot()
函数中.我尝试使用光栅包文档中提到的ratify()
和level()
函数,但我不明白如何为具有多个属性的栅格调整简化的在线示例.
如何实现这一点的任何建议将不胜感激.
# read in shapefile
shp = readOGR(".", "grid")
#convert to raster
r = raster(extent(shp))
res(r) = c(1,0.5)
ra = rasterize(shp, r)
#crop raster to desired extent
rcrop = crop(ra, extent(-12, 2, 29, 51))
# extract attribute value of interest
f = factorValues(rcrop, 1:420, layer=1, att=17, append.names=FALSE)
# here there are 420 cells in the raster and I am interested in plotting values of attribute 17 of the raster (this is currently a numeric attribute, not a factor)
#extra code to set attribute as the level to use for plotting colours???
rcrop = ratify(rcrop)
rat = levels(rcrop)[[1]] #this just extras row IDs..not what I want
#…
### plot: I want to plot the grid using 7 colours (I would ideally like to specify the breaks myself)
require(RColorBrewer)
cols = brewer.pal(7,"YlGnBu")
#set breaks
brks = seq(min(minValue(rcrop)),max(maxValue(rcrop),7))
#plot
plot(rcrop, breaks=brks, col=cols, axis.arg=arg)
Run Code Online (Sandbox Code Playgroud)
以下是非常hacky(并且对于大型栅格可能表现不佳),但我不确定是否有链接col.regions
到指定属性的方法.
rasterVis::levelplot
在标记与因子栅格相对应的颜色渐变时做得很好,虽然它提供了一个att
参数,允许您指定您感兴趣的属性,但这似乎只修改了渐变的标记.栅格单元格值控制颜色渐变如何映射到栅格,因此在我看来,我们需要自己修改单元格值.也许@OscarPerpiñán会在这里举报来证明我错了:)
我们可以创建一个简单的函数来用我们想要的任何属性替换原始单元格值:
switch_att <- function(r, att) {
r[] <- levels(r)[[1]][values(r), att]
r
}
Run Code Online (Sandbox Code Playgroud)
让我们从Natural Earth下载并导入一个小例子多边形数据集:
library(rasterVis)
library(rgdal)
require(RColorBrewer)
download.file(file.path('http://www.naturalearthdata.com',
'http//www.naturalearthdata.com/download/110m/cultural',
'ne_110m_admin_0_countries.zip'),
f <- tempfile())
unzip(f, exdir=tempdir())
shp <- readOGR(tempdir(), 'ne_110m_admin_0_countries')
Run Code Online (Sandbox Code Playgroud)
rasterize
矢量数据:
r <- rasterize(shp, raster(raster(extent(shp), res=c(1, 1))))
Run Code Online (Sandbox Code Playgroud)
并创建一些图levelplot
:
levelplot(switch_att(r, 'continent'), col.regions=brewer.pal(8, 'Set2')) +
layer(sp.polygons(shp, lwd=0.5))
Run Code Online (Sandbox Code Playgroud)
levelplot(switch_att(r, 'economy'), par.settings=BuRdTheme) +
layer(sp.polygons(shp, lwd=0.5))
Run Code Online (Sandbox Code Playgroud)
编辑
随着奥斯卡的更新rasterVis
,switch_att
上面的黑客不再是必要的.
devtools::install_github('oscarperpinan/rastervis')
levelplot(r, att='continent', col.regions=brewer.pal(8, 'Set2')) +
layer(sp.polygons(shp, lwd=0.5))
Run Code Online (Sandbox Code Playgroud)
将产生与上面第一个相同的数字.