R绘制中国地图:你去过哪些省份? (tmap版)

前段时间,一个去过哪些省份的微信小程序刷爆朋友圈:用户设定去过的省份之后,后台就自动生成地图。本人之前编写了ggplot2版本的R代码,用来绘制去过哪些省份。不过ggplot2的代码较为繁琐。这里给出tmap版。相比ggplot2,tmap的代码更容易理解。

本代码也适宜批量生成物种分布图。闲言少叙,直接贴代码了。

数据下载:http://blog.sciencenet.cn/home.php?mod=attachment&id=208159

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
setwd("...")
library(rgdal)
library(dplyr)
library(tmap)
library(tmaptools)
rm(list = ls())
## 直接读取地图shp文件
country <- readOGR("bou1_4l.shp") ## 国界
province <- readOGR("province_polygon.shp") ## 省界
sort(province$ID)
## 指定去过的省份
visited <- c( "Beijing", "Chongqing", "Fujian", "Guangdong", "Guangxi",
"Guizhou", "Hainan", "Hebei", "Heilongjiang", "Henan",
"Hubei", "Hunan", "Jiangsu", "Jiangxi", "Jilin", "Liaoning",
"NeiMongol", "Shanghai", "Sichuan", "Tianjin", "Xianggang",
"Yunnan", "Zhejiang")

province$ID <- as.character(province$ID)
province$ID2 <- ifelse(province$ID %in% visited, "Visited", "Not Visited")
province$ID2 <- as.factor(province$ID2)
## 投影转换:西安80坐标系(EPSG 2343),高斯-克吕格投影
country <- set_projection(country, projection = 2343)
province <- set_projection(province, projection = 2343)

## 保存高分辨率地图
## tiff(filename = "visitation.tiff",
## width = 4200, height = 4600, units = "px", pointsize = 12,
## compression = "lzw", res = 600)
## 显示地图

tm_shape(country) +
tm_lines(col="dodgerblue3") +
tm_shape(province) +
tm_fill("ID2",
title ="Provinces I have been to:",
palette="Pastel2") +
tm_borders("grey40", lwd = 1) +
tm_scale_bar(position=c("left", "bottom")) +
tm_compass(type = "4star", position=c("left", "top")) +
tm_layout(inner.margins=c(0.12,0.03,0.08,0.03))

## 保存地图
dev.off()

参考