我想在一个图中创建一个有九个(在这个例子中只有三个)地图的面。我已经设法绘制了几乎理想的一张地图,当我 subset
原有 shapefile
. 然而,当我试图一次绘制它们时,这是不可能的。
绘图需要有相同的图例(离散的数字作为值,而不作为值)。1, 2, 3, 4, 5
),即使有些地图的值只来自于 1
到 4
.
此外,当其中一个多边形的数据缺失时,应以灰色绘制,并附图例。NA value
.
下面的代码输出的例子在底部。可提供示例数据 此处.
path <- '~path'
muniCluster <- rgdal::readOGR(dsn=path, layer="data")
class(muniCluster)
[1] "SpatialPolygonsDataFrame"
attr(,"package")
[1] "sp"
ilum <- subset(muniCluster, CLUSTER == "CLUS_ILUM")
ilum$VALUES <- as.integer(ilum$VALUES)
ilum_df <- fortify(ilum)
ilum_tidy <- tidy(ilum)
class(ilum_df)
class(ilum_tidy)
# Recategorizes data as required for plotting
ilum$id <- row.names(ilum)
ilum_tidy <- left_join(ilum_tidy, ilum@data)
ilum_tidy$VALUES <- as.factor(ilum_tidy$VALUES)
ilum_map_v2 <- ggplot(ilum_tidy, aes(x = long, y = lat, group = group, fill = VALUES)) +
geom_polygon(color = "black", size = 0.1) +
labs(title = "Light cluster") +
scale_fill_viridis(discrete=TRUE)
ilum_map_final_v2 <- ilum_map_v2 + coord_map()
print(ilum_map_final_v2)
现在可能更容易使用 sf
包来绘制你想要的地图类型。你可以在这里看到一些例子 https:/r-spatial.github.iosfarticlessf5.html。
我从那里改编了一个例子,其中展示了如何使用 ggplot2
及其 facet_wrap
函数来为给定变量的每个级别创建一个映射。
如果你已经有了一个变量,并且有一定数量的级别,那么这里显示的一些步骤可能是不必要的。
library(sf)
library(ggplot2)
library(tidyr)
library(dplyr)
library(classInt)
library(viridis)
# Read example shapefile from sf package
nc <- st_read(system.file("shape/nc.shp", package="sf"))
# subset columns of interest as well as geometry column
# create BIR in which the variables BIR74, BIR79, NWBIR79
# become different levels of it
nc2 <- nc %>% select(BIR74, BIR79, NWBIR79, geometry) %>% gather(VAR, BIR, -geometry)
# HEre i just wanted to create 5 categories for the BIR variable
ints <- classIntervals(nc2$BIR, n = 5, style = "jenks")
nc2 <- nc2 %>% mutate(BIR_cat = cut(BIR, ints$brks, dig.lab=10))
# I just changed the levels's labels to match the output you are looking for
nc2 <- nc2 %>% mutate(values = ifelse(BIR_cat == "(3,1946]", "1",
ifelse(BIR_cat == "(1946,4706]", "2",
ifelse(BIR_cat == "(4706,9087]", "3",
ifelse(BIR_cat == "(9087,16184]", "4",
ifelse(BIR_cat == "(16184,30757]", "5", NA))))))
# Map the spatial data
ggplot() +
geom_sf(data = nc2, aes(fill = values)) +
facet_wrap(~VAR, ncol = 1) +
scale_fill_viridis(discrete=TRUE)