用ggplot2绘制Shapefile

用户143853

我想在一个绘图中创建包含九张(在此示例中只有三张)地图的构面。当我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)

在此处输入图片说明

csmontt

如今,使用该sf软件包来绘制所需的地图类型可能更容易您可以在这里查看一些示例https://r-spatial.github.io/sf/articles/sf5.html

我从那里改编了一个示例,该示例显示了如何使用ggplot2facet_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) 

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章