R语言绘制省市热力地图
加载包 install.packages(“mapdata”)install.packages(“maptools”)
install.packages(“ggplot2”)
install.packages(“plyr”)
library(mapdata)
library(maps)
library(sp)
library(maptools)
library(ggplot2)
library(plyr)
install.packages(“rgdal”)
library(rgdal)
install.packages(“mapproj”)
library(mapproj)
绘制中国地图 china_map=readShapePoly(“bou2_4p.shp”)
plot(china_map)
ggplot2图形绘制 ggplot(china_map,aes(x=long,y=lat,group=group))+
geom_polygon(fill=“white”,colour=“black”)+
coord_map(“polyconic”)+
theme(
panel.grid=element_blank(),
panel.background=element_blank(),
axis.text=element_blank(),
axis.ticks=element_blank(),
axis.title=element_blank(),
legend.position=c(0.2,0.3)
)
x<-china_map@data
xs<-data.frame(x,id=seq(0:924)-1)#地图中共计有925个地域信息
china_map1<-fortify(china_map)
china_map_data<-join(china_map1,xs,type=“full”)#基于id进行连接
unique(china_map@data$NAME)#查看地图数据中保存的地域名称,编辑自己的数据与其一致
mydata<-read.csv(“data_dt.csv”,header=T,as.is=T)
china_data <- join(china_map_data, mydata, type=“full”)#基于NAME字段进行连接,NAME字段来自于地图文件中
绘制热力图 ggplot(china_data,aes(x=long,y=lat,group=group,fill=ratio))+
geom_polygon(colour=“grey40”)+
scale_fill_gradient(low=“white”,high=“red”)+
coord_map(“polyconic”)+
theme(
panel.grid=element_blank(),
panel.background=element_blank(),
axis.text=element_blank(),
axis.ticks=element_blank(),
axis.title=element_blank(),
legend.position=c(0,0.2)
)##参数“ratio”为我们要展现的数据指标,基于该指标绘制热力图
添加地址标签 province_city<-read.csv(“pcity.csv”,header=T,as.is=T)#获取省会城市坐标
ggplot(china_data,aes(long,lat))+
geom_polygon(aes(group=group,fill=ratio),colour=“grey”,size=0.01)+
scale_fill_gradient(low=“white”,high=“red”)+
coord_map(“polyconic”)+
geom_text(aes(x=jd,y=wd,label=name),data=province_city,colour=“black”,size=2.5)+
theme(
panel.grid=element_blank(),
panel.background=element_blank(),
axis.text=element_blank(),
axis.ticks=element_blank(),
axis.title=element_blank()
)
页:
[1]