在R中导出数据与制作地图
本部分将带您实践所学知识,并将其与R语言衔接,重温我们过去掌握的内容。
我们将首先学习在R中制作地图的基础技巧。
在R中创建地图
现在我们将切换到R环境,学习如何制作精美的地图。
开始前,若未使用R项目,请记得设置工作目录:
setwd("...")
# 请将目录设置为您的数据文件夹路径!
用R制作精美地图
R能创建出版级的高质量地图,省去了将文件导出至ArcGIS或QGIS等软件进行后期处理的麻烦。
制图如同艺术创作。优秀的地图能极大提升成果展示效果,这需要技巧与实践。结合R强大的数据处理与可视化包,我们可以突破静态地图的局限。本节将学习两种地图的基础制作方法:
- 静态地图
- 交互式地图
我们将使用’tmap’包——这个语法类似ggplot2的强大工具,能通过tmap_mode()
用相同代码生成静态与交互式地图。
library(tmap)
library(spData)
使用tmap前请牢记:所有函数都有详细帮助文档。我们将介绍基础功能,鼓励您自行探索更多选项。
静态地图基础
我们将先用示例数据演示基础操作,再使用本章真实数据制作可出版的地图。
静态地图是最传统的地理空间分析输出形式。tmap语法将输入数据与可视化美学分离,同一数据集可通过多种方式呈现(栅格、点、面等)。
使用’spData’包中的world数据集(含世界银行部分指标)进行演示:
data(world)
# 添加填充层
tm_shape(world) + tm_fill()
# 添加边界层
tm_shape(world) + tm_borders()
# 组合填充与边界
tm_shape(world) + tm_fill() + tm_borders()
类似ggplot,tmap对象可命名存储后调用:
map1 <- tm_shape(world) + tm_fill() + tm_borders()
map1
添加新对象(如另一个shapefile)使用+ tm_shape(new_obj)
语法,后续美学函数将应用于该对象,直到添加新对象为止:
tm_shape(world) + tm_borders() +
tm_shape(urban_agglomerations) + tm_dots(size = "population_millions")
可通过变量字段或常量值调整地图美学。常用参数包括:
- 面填充色:
fill
- 边界色:
col
- 透明度:
fill_alpha
/col_alpha
- 线宽:
lwd
- 线型:
lty
使用tmap_arrange
并列显示多图:
ma1 = tm_shape(world) + tm_fill(fill = "red")
ma6 = tm_shape(world) + tm_fill(fill = "red", fill_alpha = 0.3) +
tm_borders(col = "blue", col_alpha = 0.6, lwd = 3, lty = 2)
tmap_arrange(ma1, ma2, ma3, ma4, ma5, ma6)
基于变量值着色时,可使用默认分段或自定义分段。fill.scale
参数控制调色板与数值分段,此处使用蓝色系brewer.bu_gn
调色板展示各国人口:
breaks = c(0, 2, 5, 10, 100, 500, 2000) * 1000000 # 自定义分段
tm_shape(world) +
tm_polygons(fill = "pop",
fill.scale = tm_scale(values = "brewer.bu_gn", breaks = breaks))
通过fill.legend
参数精细控制图例:
tm_shape(world) +
tm_polygons(fill = "pop",
fill.legend = tm_legend(title = "Population",
orientation = "landscape",
position = tm_pos_out("center", "bottom")))
添加指北针与比例尺:
tm_shape(world) +
tm_polygons(fill = "pop") +
tm_compass(position = c("left", "bottom")) +
tm_scalebar(position = c("left", "bottom"))
交互式地图
2015年发布的’leaflet’包革新了R中的交互式网络地图制作。tmap通过tmap_mode("view")
可一键切换为交互模式(注意比例尺和指北针在此模式下不显示):
tmap_mode("view")
tm_shape(world) + tm_polygons(fill = "pop")
交互地图支持点击查询属性、切换底图,可保存为HTML文件分享或嵌入网页。
制作专业地图案例
从GEE导出影像
我们将在GEE中生成2020年火灾发生日期影像,使用MCD64A1火烧迹地数据集(代码参见此处)。
在R中制图
加载必要包:
library(sf) # 空间矢量数据处理
library(terra) # 栅格数据处理
library(tidyverse)
library(tmap)
导入GEE导出的数据:
PAs <- st_read("./Data/PAs.shp") # 读取保护区面数据
BurntA <- rast("./Data/BurntAreas.tif") # 读取火烧迹地栅格
将背景值-9999替换为NA:
BurntA[BurntA == -9999] <- NA
plot(BurntA)
制作静态地图:
tmap_mode("plot")
tm_shape(BurntA) +
tm_raster(col.scale = tm_scale_continuous(values = heat.colors(9)),
col.legend = tm_legend("Burn date")) +
tm_shape(PAs) + tm_borders(lty = 2) +
tm_compass(position = c("right", "top")) +
tm_scalebar(position = c("left", "bottom"), width = 14) +
tm_layout(frame = FALSE, legend.outside = T) +
tm_add_legend(type = "lines", labels = "Conservancies")
制作交互地图:
tmap_mode("view")
tm_shape(BurntA) + tm_raster(palette = heat.colors(9), title = "Burn date") +
tm_shape(PAs) + tm_borders(lty = 2)