发一篇教大家如何用R语言画路线图的攻略~
~\(≧▽≦)/~
题目是这样的:
利用R的地图包,提取武汉地图,并在图上标注一条从华中师范大学北门到黄鹤楼的路线.
首先,读取需要用到的R包~
library(maptools)
library(sp)
library(ggplot2)
library(mapproj)
再然后,在国家基础地理信息中心上下载地级市的shp地图包~这个网站我当时试了好多次还是登不上去,又从网上找了一个数据包~
当然你找百度地图,谷歌地图神马的,只要能拿到市级地图都行~R语言自带的包没有精确到市级。。。
http://pan.baidu.com/s/1hs03gUg(如果分享过期了可以上网搜索BOUNT_poly.shp)
读入地级市包里的这个文件
mydat = readShapePoly("d:/rstudy/BOUNT_poly.shp")
按照99年制定的名字标准找到武汉市
tmp = iconv(mydat$NAME99, from = "GBK")
grep("武汉", tmp, value = TRUE)
显示武汉市对应ADCODE99编码
mydat$ADCODE99[grep("武汉", tmp)]
接下来就是把地图数据从地图包里找出来啦~稍微改一下名称~
Wuhan = mydat[substr(as.character(mydat$ADCODE99), 1, 4) == "4201",]
mysh = fortify(Wuhan)
mysh = transform(mysh, id = iconv(id, from = 'GBK'), group = iconv(group, from = 'GBK'))
head(mysh, n = 2)
names(mysh)[1:2] = c("x","y")
为了好看,要涂上漂亮哒颜色~不过作为一个重度选择困难症,还是用随机数涂颜色啦~
(其实是因为网上的教程里有现成的随机数涂色╮(╯▽╰)╭)
先弄一串随机数把~
myepidat = data.frame(id = unique(sort(mysh$id)))
myepidat$rand = runif(length(myepidat$id))
myepidat
接下来查出华师和黄鹤楼的大致经纬度,我在百度地图找的,四舍五入一下~
然后准备好名字标签。
多个多维向量做图处理的时候记得转化成数据框哟~
E <- c(114.31,114.37)
N <- c(30.55,30.52)
place <- c('黄鹤楼','华师')
data <- data.frame(E,place,N)
最后画出地图,涂色,标出目标点,连线。(可能是游戏打多了,用的红到绿的渐变色,地点用的是黄色,连线用蓝色~不要嘲笑我哒审美,我可是试了好多颜色哒~)
╮(╯▽╰)╭
csmap = ggplot(myepidat) +
geom_map(aes(map_id = id, fill = rand), color = "white", map = mysh) +
scale_fill_gradient(high = "red",low = "darkgreen") +
geom_point(aes(E, N),data = data,colour="yellow") +
geom_line(aes(E, N),data = data, colour = "blue",size = 1.5)+
geom_text(data = data,aes(E, N, label = place),hjust = 1.2,size = 3) +
expand_limits(mysh) +
coord_map()
print(csmap)
全部代码:
library(maptools)
library(sp)
library(ggplot2)
library(mapproj)
mydat = readShapePoly("d:/rstudy/BOUNT_poly.shp")
tmp = iconv(mydat$NAME99, from = "GBK")
grep("武汉", tmp, value = TRUE)
grep("武汉", tmp)
mydat$ADCODE99[grep("武汉", tmp)]
Wuhan = mydat[substr(as.character(mydat$ADCODE99), 1, 4) == "4201",]
mysh = fortify(Wuhan)
mysh = transform(mysh, id = iconv(id, from = 'GBK'), group = iconv(group, from = 'GBK'))
head(mysh, n = 2)
names(mysh)[1:2] = c("x","y")
myepidat = data.frame(id = unique(sort(mysh$id)))
myepidat$rand = runif(length(myepidat$id))
myepidat
E <- c(114.31,114.37)
N <- c(30.55,30.52)
place <- c('黄鹤楼','华师')
data <- data.frame(E,place,N)
csmap = ggplot(myepidat) +
geom_map(aes(map_id = id, fill = rand), color = "white", map = mysh) +
scale_fill_gradient(high = "red",low = "darkgreen") +
geom_point(aes(E, N),data = data,colour="yellow") +
geom_line(aes(E, N),data = data, colour = "blue",size = 1.5)+
geom_text(data = data,aes(E, N, label = place),hjust = 1.2,size = 3) +
expand_limits(mysh) +
coord_map()
print(csmap)
运行结果:
参考资料:
[1] 姜晓东. R 绘制中国地图,并展示流行病学数据 https://cosx.org/2014/08/r-maps-for-china
[2] blbailei. 如何向ggplot图中添加参考线和标准的例子http://www.dataguru.cn/thread-274407-1-1.html