我想在一个图中创建一个包含9个(在本例中只有3个)映射的facet。当我从原始的shapefile subset时,我已经成功地绘制了几乎理想的一张地图。然而,当我试图一次将它们全部绘制出来时,这是不可能的。
即使某些映射只有从1到4的值,绘图也需要具有相同的图例(离散值与值1, 2, 3, 4, 5)。
此外,当其中一个多边形缺少数据时,它应该以灰色绘制,并带有图例NA value。
下面代码的输出示例在底部。一个示例数据是available here。
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)

发布于 2020-06-18 06:47:46
现在,使用sf包来绘制您想要的地图类型可能更容易。你可以在这里看到一些例子https://r-spatial.github.io/sf/articles/sf5.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)

https://stackoverflow.com/questions/62435609
复制相似问题