R语言 ggmap 地图
第一部分---地图 包的调用
安装maps包
install.packages("manipulate")
install.packages('maps')
library(maps)
在安装Maps包过程中遇到的问题
cannot open compressed file 'maps/DESCRIPTION', probable reason 'No such file or directory'
Error in install.packages : cannot open the connection
解决:手动下载zip包,然后运行下面命令
跟网络情况有关
install.packages('I:\自己学习\R语言做ppt\maps_3.2.0.zip', repos = NULL, type = "source")
这个包中本来就存有世界地图和美国地图数据,可以画出地图如下:
世界地图
map("world", fill = TRUE, col = rainbow(200),
ylim = c(-60, 90), mar = c(0, 0, 0, 0))
title("世界地图")
世界地图
美国地图
map("state", fill = TRUE, col = rainbow(209),
mar = c(0, 0, 2, 0))
title("美国地图")
美国地图
在Maps包中没有中国地图,可以安装mapdata包来绘制中国地图
中国地图
install.packages("mapdata")
library(mapdata)
map("china", col = "red4", ylim = c(18, 54), panel.first = grid())
title(" 中国地图")
ggmap
下面演示的都是ggmap这个包的功能,非常强大
install.packages("ggmap")
library(ggmap)
返回宁波的经纬度信息
geocode("ningbo")
宁波经纬度
返回浙江大学的信息
geocode("Zhejiang University",output = "more")
浙江大学信息
浙江大学与宁波大学之间的走路距离
mapdist("Zhejiang University","Ningbo University","walking")
浙江大学与宁波大学之间的走路距离
中国地图 用ggmap画出
map <- get_map(location = 'China', zoom = 4)
ggmap(map)
中国地图
宁波的公路地图数据
map <- get_map(location = 'Ningbo', zoom = 10, maptype = 'roadmap')
ggmap(map)
宁波市公路图
浙江大学 卫星地图数据
浙江大学卫星图map <- get_map(location = 'zhejiang University', zoom = 14,
maptype = 'satellite')
ggmap(map)
第二部分----中国航线可视化
此处航线可视化的实现是参考统计之都肖凯老师的文章,链接地址如下
航线可视化--肖凯
航线数据下载网址如下:
航线数据下载网址
航线可视化
library(ggmap)
data.port<-read.csv('I:\自己学习\R语言做ppt\航线数\airports.dat.txt',F)
data.line<-read.csv('I:\自己学习\R语言做ppt\航线数据\routes.dat.txt',F)
library(stringr)
// 找到中国的机场
portinchina <- str_detect(data.port[,'V4'], "China")
strchinaport <- data.port[portinchina,]
//去除少数几个没有编号的机场
chinaport <-strchinaport[strchinaport$V5!='',
c('V3','V5','V7','V8','V9')]
names(chinaport) <- c('city','code','lan','lon','att')
//机场数据展示
机场数据
// 找出国内航班
lineinchina <- (data.line[,'V3'] %in% chinaport$code) & (data.line[,'V5'] %in% chinaport$code)
chinaline <- data.line[lineinchina,c('V3','V5','V9')]
names(chinaline) <- c('source','destination','equipment')
//航班数据展示
航班数据
//构建一个函数,根据机场编码得到经纬度
findposition <- function(code) {
find <- chinaport$code==code
x <- chinaport[find,'lon']
y <- chinaport[find,'lan']
return(data.frame(x,y))
}
//将机场编码转为经纬度
from <- lapply(as.character(chinaline$source),findposition)
from <- do.call('rbind',from)
from$group <- 1:dim(from)[1]
names(from) <- c('lon','lan','group')
to <- lapply(as.character(chinaline$destination),findposition)
to <- do.call('rbind',to)
to$group <-1:dim(to)[1]
names(to) <-c('lon','lan','group')
data.line <- rbind(from,to)
temp<- data.line[data.line$group<100,]
library(ggmap)
// 用ggmap包从google读取地图数据,并将之前的数据标注在地图上。
ggmap(get_googlemap(center = 'china', zoom=4,
maptype='roadmap'),extent='device')+
geom_point(data=chinaport,aes(x=lon,y=lan),
colour = 'red4',alpha=0.8)+
geom_line(data=data.line,aes(x=lon,y=lan,group=group),
size=0.1,alpha=0.05,color='red4')
最后绘制出航线图如下所示:
中国航线图
再次感谢参考引用:
参考文章---R 时代,你要怎样画地图?苏建冲