使用geojson和ggplot2创建颜色分段地图

6
我正在尝试使用Rgeojsonggplot2制作尼泊尔各地区的人类贫困指数的区域分布图。
我从这里读取了尼泊尔各地区的geojson数据。
我在这里这里看到了一些示例。
这是我的做法:
# Read geojson data for nepal with districts
library(tidyverse)
library(geojsonio)
#> 
#> Attaching package: 'geojsonio'
#> The following object is masked from 'package:base':
#> 
#>     pretty
spdf <- geojson_read("nepal-districts.geojson",  what = "sp")
##https://github.com/mesaugat/geoJSON-Nepal/blob/master/nepal-districts.geojson




#tidy data for ggplot2
library(broom)
spdf_fortified <- tidy(spdf)
#> Regions defined for each Polygons

# plot
ggplot() +
    geom_polygon(data = spdf_fortified, aes( x = long, y = lat, group = group)) +
    theme_void() +
    coord_map()

names(spdf_fortified)
#> [1] "long"  "lat"   "order" "hole"  "piece" "group" "id"



#Now read the data to map to districts
data=read.csv("data.csv")
#data from here
#https://github.com/opennepal/odp-poverty/blob/master/Human%20Poverty%20Index%20Value%20by%20Districts%20(2011)/data.csv

#filter and select data to reflect Value of HPI in various districts
data <- data %>% filter(Sub.Group=="HPI") %>% select(District,Value)


head(data)
#>       District Value
#> 1       Achham 46.68
#> 2 Arghakhanchi 27.37
#> 3        Banke 32.10
#> 4      Baglung 27.33
#> 5      Baitadi 39.58
#> 6      Bajhang 45.32

# Value represents HPI value for each district.

#Now how to merge and fill Value for various districts
#
#
#
#

这段内容是关于编程的,创建于2018年6月14日,使用了reprex package(v0.2.0)。

如果我能将spdf_fortifieddata合并到merged_df中,我认为可以使用以下代码生成等值线地图:

ggplot(data = merged_df, aes(x = long, y = lat, group = group)) + geom_polygon(aes(fill = Value), color = 'gray', size = 0.1)

合并两个数据需要帮助吗?

1个回答

12

不想颠覆你的整个系统,但是我最近经常使用sf,发现它比sp更易于使用。 ggplot也有很好的支持,因此您可以使用geom_sf进行绘图,通过将变量映射到fill来制作等值线图:

library(sf)
library(tidyverse)

nepal_shp <- read_sf('https://raw.githubusercontent.com/mesaugat/geoJSON-Nepal/master/nepal-districts.geojson')
nepal_data <- read_csv('https://raw.githubusercontent.com/opennepal/odp-poverty/master/Human%20Poverty%20Index%20Value%20by%20Districts%20(2011)/data.csv')

# calculate points at which to plot labels
centroids <- nepal_shp %>% 
    st_centroid() %>% 
    bind_cols(as_data_frame(st_coordinates(.)))    # unpack points to lat/lon columns

nepal_data %>% 
    filter(`Sub Group` == "HPI") %>% 
    mutate(District = toupper(District)) %>% 
    left_join(nepal_shp, ., by = c('DISTRICT' = 'District')) %>% 
    ggplot() + 
    geom_sf(aes(fill = Value)) + 
    geom_text(aes(X, Y, label = DISTRICT), data = centroids, size = 1, color = 'white')

两个数据框中有三个地区的命名方式不同,需要进行清理,但这是一个相对不需要花费太多时间就能开始的很好的起点。

ggrepel::geom_text_repel可以避免标签重叠的可能性。


清晰明了的解释。谢谢。有没有一种方法可以给区域添加标签? - Suman Khanal
当然可以,使用geom_textgeom_label即可。但是它们需要xy美学属性,因此您需要预先计算一些内容,例如使用sf::st_centroid(您仍然需要解包其结果)。我已经进行了编辑以进行演示。 - alistaire

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接