R语言与地图

本文是对统计之都R绘制中国地图,并展示流行病学数据的练习,主要讲解使用R语言绘制地图

数据下载链接见原文,5M的东西放github上着实污染环境

map函数

map函数是R语言绘制地图最简单的方法了

1
2
3
library(maps)
library(mapdata)
map("china")

ggplot2

中国地图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
library(maptools)
library(mapproj)
library(ggplot2)
# 设置工作目录并导入地图数据
setwd("/Users/lixinyao/Downloads/maps_data/maps/bou1")
mydata1 = readShapePoly("bou1_4p.shp")
head(mydata1@data)
# ggplot2里的fortify函数转化数据框,未来用broom package
head(fortify(mydata1))
# geom_polygon绘制地图
mymap = ggplot(data = fortify(mydata1)) +
geom_polygon(aes(long, lat, group = id), color = "black", fill = NA) +
coord_map()
mymap

中国分省市地图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 设置工作目录并导入地图数据
setwd("/Users/lixinyao/Downloads/maps_data/maps/bou2")
mydata2 = readShapePoly("bou2_4p.shp")
# 查看mydata2的列名
names(mydata2@data)
# 统计不同省份个数,iconv进行格式转化
table(iconv(mydata2$NAME,from = "GBK"))
# fortify转换为数据框
head(fortify(mydata2))
# geom_polygon绘制地图
mymap = ggplot(data = fortify(mydata2)) +
geom_polygon(aes(long, lat, group = id), color = "black", fill = NA) +
coord_map()
mymap

绘制北京市地图

可以看到这份地图数据有点老,期待新地图的出现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 导入北京的地图数据
mydata = readShapePoly("/Users/lixinyao/Downloads/maps_data/maps/bou4/BOUNT_poly.shp")
# 北京的ADCODE99编号前两位是11
beijing = mydata[substr(as.character(mydata$ADCODE99), 1, 2) == '11',]
# 转化为数据框
library(gpclib)
gpclibPermit()
gpclibPermitStatus()
mybj = fortify(beijing, region = 'NAME99')
mybj = transform(mybj, id = iconv(id, from = 'GBK'), group = iconv(group, from = 'GBK'))
head(mybj)
# 取出北京坐标并转化成数据框
tmp = coordinates(beijing)
tmp = as.data.frame(tmp)
head(tmp)
tmp$names = iconv(beijing$NAME99, from = 'GBK')
# 绘制地图,mac下加family
mymap = ggplot(data = fortify(mybj)) +
geom_polygon(aes(long, lat, group = id), color = "black", fill = NA) +
coord_map() +
geom_text(aes(V1,V2,label=names),family="STKaiti",data=tmp)
mymap

喂他一颗糖