ggplot繪制map
R語言可以進行數(shù)據(jù)分析,也可以進行地圖繪制,而且非常簡潔,快速。
雖然Arcgis基于桌面可視化操作,能夠進行空間分析,但是唯一不足的就是操作步驟繁瑣而且一不小心,就要從頭再來,可重復性較低。
這篇文章主要講述如何利用R語言中的ggplot與sf繪制帶有指北針、圖列與標尺的地圖

數(shù)據(jù)
我們下載非洲地區(qū)54個國家的圖層Afirca.json保存在本地。然后加載包去讀取。然后在ggplot中使用 geom_sf來簡單畫出非洲地區(qū)的輪廓
library(tidyverse)
library(sf)
library(ggspatial)
library(ggthemes)
# https://geojson-maps.ash.ms/
africa <- read_sf("africa.json")
# plot
africa %>%
ggplot() +
geom_sf()
# populations with colors
ggplot(africa) +
geom_sf(aes(geometry = geometry, fill = pop_est))

指北針
一張標準的地圖需要有比例尺,地圖及指北針,所以這次我們加上比例尺與指北針,通過ggspatial包,調(diào)用annotation_scale來增加比例尺。location = "bl"是調(diào)整比例尺位置, width_hint = 0.3調(diào)整比例的長度。
annotation_north_arrow則是用來添加指北針。style =north_arrow_nautical來更改指北針的類型,主要有north_arrow_orienteering;north_arrow_fancy_orienteering;north_arrow_minimal與north_arrow_nautical四種類型,其他參數(shù)可help(annotation_north_arrow)查看。
# with scales and north_arrow
ggplot(africa) +
geom_sf(aes(geometry = geometry, fill = pop_est)) +
annotation_scale(location = "bl", width_hint = 0.4) +
annotation_north_arrow(location = "tr", which_north = "true",
pad_x = unit(0.05, "in"), pad_y = unit(0.05, "in"),
style = north_arrow_nautical)

背景調(diào)整
如果不喜歡有grid的背景,可以根據(jù)喜好,調(diào)節(jié)自己喜歡的背景
這里我們采用, theme_light()白色網(wǎng)格背景。更多背景設置,請見ggplot2 主題背景設置
# with blank themes
ggplot(africa) +
geom_sf(aes(geometry = geometry, fill = pop_est)) +
annotation_scale(location = "bl", width_hint = 0.4) +
annotation_north_arrow(location = "tr", which_north = "true",
pad_x = unit(0.05, "in"), pad_y = unit(0.05, "in"),
style = north_arrow_nautical) +
theme_light()

圖例顏色
默認的圖例顏色是blue色調(diào),我們可以根據(jù)
來更改紅色基準的色調(diào)。
legend 是默認的分段方式,我們可以根據(jù)需要設定成4分類,或者更改圖例的距離。
# with colors
ggplot(africa) +
geom_sf(aes(geometry = geometry, fill = pop_est)) +
scale_fill_gradientn(colours=brewer.pal(5,"Reds"))+
annotation_scale(location = "bl", width_hint = 0.4) +
annotation_north_arrow(location = "tr", which_north = "true",
pad_x = unit(0.05, "in"), pad_y = unit(0.05, "in"),
style = north_arrow_nautical) +
theme_light()
# for 4 categories
africa %>% mutate( new=cut(pop_est,b = 4)) %>%
ggplot() +
geom_sf(aes(geometry = geometry, fill = new)) +
annotation_scale(location = "bl", width_hint = 0.4) +
annotation_north_arrow(location = "tr", which_north = "true",
pad_x = unit(0.05, "in"), pad_y = unit(0.05, "in"),
style = north_arrow_nautical) +
theme_light()
# set for sacles
my_breaks = c(0,3207562,10401245,18419935,20644434,149229090 )
ggplot(africa) +
geom_sf(aes(geometry = geometry, fill = pop_est)) +
scale_fill_gradient(name = "count",
breaks = my_breaks, labels = my_breaks)
#
ggplot(africa) +
geom_sf(aes(geometry = geometry, fill = pop_est)) +
scale_fill_gradient(name = "count",
breaks = my_breaks, labels = my_breaks, guide="legend")


關于更多顏色設置ggplot2: Elegant Graphics for Data Analysis
legend分類legend and labels