在多边形中创建一个网格并使用 geom_tile 填充它
Create a Grid in Polygon and fill it using geom_tile
我想问一下如何在多边形内创建一个网格,然后用网格坐标上的颜色数据填充网格。
例如,用 5 种颜色或类似颜色中的随机颜色填充每个网格多边形。
示例数据:
library(leaflet)
library(ggplot2)
library(sf)
library(spdep)
URL <- "https://biogeo.ucdavis.edu/data/gadm3.6/Rsp/gadm36_CZE_0_sp.rds"
data <- readRDS(url(URL))
ggplot() +
geom_polygon(data = data, aes(x=long, y = lat, group = group), color = "black", fill = F)
这是一个简单的示例,使用 st_make_grid()
在多边形内创建网格,并使用 brewer.pal()
创建调色板来填充网格。
library(tidyverse)
library(sf)
#> Linking to GEOS 3.6.2, GDAL 2.2.3, PROJ 4.9.3
p1 <- st_polygon(list(rbind(c(0,0),c(1,0),c(1,1),c(0,1), c(0,0))))
grid <- st_make_grid(p1, n = 2)
number_of_cells <- length(grid)
colors <- RColorBrewer::brewer.pal(number_of_cells, name = 'PuBuGn')
ggplot(grid) +
geom_sf(fill = colors)
#Example using multipolygon shapefile
nc <- read_sf(system.file("shape/nc.shp", package="sf"))
#st_combine is used to make a single polygon since nc is a multipolygon shapefile
nc_grid <- st_make_grid(st_combine(nc), n = 20)
ggplot() + geom_sf(data = st_union(nc)) + geom_sf(data =nc_grid, fill = NA)
nc_grid_sf <- as_Spatial(nc_grid) %>% st_as_sf() %>% st_transform(st_crs(nc))
# Keep grid only within polygon
st_intersection(nc_grid, st_union(nc)) %>%
ggplot() +
geom_sf()
#> although coordinates are longitude/latitude, st_intersection assumes that they are planar
由 reprex package (v0.3.0)
于 2020-01-15 创建
我想问一下如何在多边形内创建一个网格,然后用网格坐标上的颜色数据填充网格。
例如,用 5 种颜色或类似颜色中的随机颜色填充每个网格多边形。
示例数据:
library(leaflet)
library(ggplot2)
library(sf)
library(spdep)
URL <- "https://biogeo.ucdavis.edu/data/gadm3.6/Rsp/gadm36_CZE_0_sp.rds"
data <- readRDS(url(URL))
ggplot() +
geom_polygon(data = data, aes(x=long, y = lat, group = group), color = "black", fill = F)
这是一个简单的示例,使用 st_make_grid()
在多边形内创建网格,并使用 brewer.pal()
创建调色板来填充网格。
library(tidyverse)
library(sf)
#> Linking to GEOS 3.6.2, GDAL 2.2.3, PROJ 4.9.3
p1 <- st_polygon(list(rbind(c(0,0),c(1,0),c(1,1),c(0,1), c(0,0))))
grid <- st_make_grid(p1, n = 2)
number_of_cells <- length(grid)
colors <- RColorBrewer::brewer.pal(number_of_cells, name = 'PuBuGn')
ggplot(grid) +
geom_sf(fill = colors)
#Example using multipolygon shapefile
nc <- read_sf(system.file("shape/nc.shp", package="sf"))
#st_combine is used to make a single polygon since nc is a multipolygon shapefile
nc_grid <- st_make_grid(st_combine(nc), n = 20)
ggplot() + geom_sf(data = st_union(nc)) + geom_sf(data =nc_grid, fill = NA)
nc_grid_sf <- as_Spatial(nc_grid) %>% st_as_sf() %>% st_transform(st_crs(nc))
# Keep grid only within polygon
st_intersection(nc_grid, st_union(nc)) %>%
ggplot() +
geom_sf()
#> although coordinates are longitude/latitude, st_intersection assumes that they are planar
由 reprex package (v0.3.0)
于 2020-01-15 创建