ggplot绘制map
R语言可以进行数据分析,也可以进行地图绘制,而且非常简洁,快速。
虽然Arcgis基于桌面可视化操作,能够进行空间分析,但是唯一不足的就是操作步骤繁琐而且一不小心,就要从头再来,可重复性较低。
这篇文章主要讲述如何利用R语言中的ggplot
与sf
绘制带有指北针、图列与标尺的地图
数据
我们下载非洲地区54个国家的图层Afirca.json保存在本地。然后加载包去读取。然后在ggplot中使用 geom_sf
来简单画出非洲地区的轮廓
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
包,调用annotation_scale
来增加比例尺。location = "bl"
是调整比例尺位置, width_hint = 0.3
调整比例的长度。
annotation_north_arrow
则是用来添加指北针。style =north_arrow_nautical
来更改指北针的类型,主要有north_arrow_orienteering
;north_arrow_fancy_orienteering
;north_arrow_minimal
与north_arrow_nautical
四种类型,其他参数可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)
背景调整
如果不喜欢有grid的背景,可以根据喜好,调节自己喜欢的背景
这里我们采用, theme_light()
白色网格背景。更多背景设置,请见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色调,我们可以根据
来更改红色基准的色调。
legend 是默认的分段方式,我们可以根据需要设定成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
参考
- Geospatial Visualization
- sf 与指北针
- geocompkg | metapackage for the Gecomputation with R book
- This repository contains the source for the book Geospatial Visualization.
- Chapter 8: Making maps with R
- ggplot2 主题背景设置