用R绘制带省界和省会的中国地图

首先你得从网上下载中国地图和省会城市的shapefile文件,很多地方提供下载。代码:

## install.packages('maptools') # 还没安装maptools的执行此语句
library(maptools)
library(rgdal)
str.crs <- " +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
china <- readShapePoly("china.map/bou2_4p.shp", proj4string = CRS(str.crs))
## 绘制中国地图
par(mar = c(2, 2, 0.1, 0.1))
plot(china, axes = TRUE, type = "n")
## 给不同省标上不同颜色
province <- sort(unique(china@data$NAME))
n <- length(province)
set.seed(1949)
color <- sample(grep("^[^(gr|bl|wh)]+", colors(), value = T), n)
for (i in 1:n) {
    plot(subset(china, china@data$NAME == province[i]), add = TRUE, col = color[i],
        border = "gray")
}
## 添加省会城市
capital <- readShapePoints("china.map/res1_4m.shp", proj4string = CRS(str.crs))
cap.name <- iconv(capital@data$NAME, "gbk", "utf8")
cap.coords <- coordinates(capital)
n <- length(cap.name)
plot(capital, add = TRUE, pch = 20, cex = 0.8)
pos <- rep(4, times = n)
spec.name <- c("呼和浩特", "成都", "西宁", "太原", "合肥", "武汉",
    "长沙", "银川", "南宁", "澳门")
pos[cap.name %in% spec.name] <- 2
spec.name <- c("北京", "南京", "上海", "广州")
pos[cap.name %in% spec.name] <- 3
text(cap.coords, labels = cap.name, cex = 0.7, pos = pos, offset = 0.2)
用R绘制带省界和省会的中国地图_第1张图片

作者: ZGUANG@LZU

Created: 2015-12-18 五 16:47

Emacs 24.4.1 (Org mode 8.2.10)

你可能感兴趣的:(R语言基础)