【问题标题】:converting sf to raster using predefined cell size and plot it使用预定义的像元大小将 sf 转换为栅格并绘制它
【发布时间】:2021-10-02 19:06:13
【问题描述】:

nz_heightnz 存在于 spData 包中。

  1. nz_height - sf 类数据集 - 新西兰前 101 个最高点。
  2. nz - sf 类数据 - 代表新西兰 16 个地区的多边形。

下面是使用tmap()进行可视化的图

你能帮我创作吗

  1. nz_raster(栅格类),像元大小 = 100 公里乘 100 公里,每个像元中包含峰值数
  2. 绘制 nz_raster。
# load packages
library(tidyverse)
library(sf)
library(raster)
library(spData)
library(tmap)


# vector plot of peaks
tm_shape(nz) + 
  tm_polygons(col = "white") + 
  tm_shape(nz_height) + 
  tm_symbols(col = "red") + 
  tm_scale_bar()

【问题讨论】:

    标签: r raster sf tmap


    【解决方案1】:

    您可以使用raster 包或其继任者terra 对点进行栅格化:

    # Load packages
    packs <- list("tidyverse", "raster", "sf", "terra")
    lapply(packs, require, character.only = T)
    
    # raster version
    nz_height <- st_transform(nz_height, crs = "+proj=moll +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs") %>% 
      as("Spatial")
    nz_raster <- raster(resolution = 100000, crs = "+proj=moll +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs", 
      xmn = 13600000, xmx = 15100000, ymn = -5300000, ymx = -4700000) %>% 
      rasterize(nz_height, ., field = "elevation", fun = "count", background = 0)
    
    # terra version
    nz_height <- st_transform(nz_height, crs = "+proj=moll +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs") %>% 
      vect()
    nz_raster <- rast(resolution = 100000, crs = "+proj=moll +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs", 
      xmin = 13600000, xmax = 15100000, ymin = -5300000, ymax = -4700000) %>% 
      rasterize(nz_height, ., fun = length, background = 0)
    

    代码使用Mollweide等面积投影,即网格单元同样大。

    您可以通过这些包中的plot() 函数绘制光栅对象。其他选项例如rasterVis::gplot()ggplot2::geom_raster()tmap::tm_raster()

    【讨论】:

      最近更新 更多