1、绘制中国地图
library("maptools") china_map = readShapePoly("D:/Astatistics/R/画热力图数据材料/中国省级地图空间数据文件/bou2_4p.shp") # 读取地图空间数据 plot(china_map)#可以不画
2*、改变投影方式
library(ggplot2) ggplot(china_map,aes(x=long,y=lat,group=group)) + geom_polygon(fill="white",colour="grey") + coord_map("polyconic")
3、加载和拼接行政信息
x <- [email protected] #读取行政信息 xs <- data.frame(x,id=seq(0:924)-1) #含岛屿共925个形状 library(ggplot2) china_map1 <- fortify(china_map) #转化为数据框 library(plyr) china_map_data <- join(china_map1, xs, type = "full") #合并两个数据框
4、制作业务工作表,保存为csv。需要NAME行(一定命名为NAME),和绘图指标C1
其中,查看数据包里各省名称
unique([email protected]$NAME)
5、读取业务指标,与地理数据合并
mydata <- read.csv("c:/rstudy/geshengzhibiao.csv") #读取指标数据,csv格式 china_data <- join(china_map_data, mydata, type="full") #合并两个数据框 提示:Joining by: NAME
6、绘制地图
ggplot(china_data, aes(x = long, y = lat, group = group,fill = zhibiao)) +
geom_polygon(colour="grey40") +
scale_fill_gradient(low="white",high="steelblue") + #指定渐变填充色,可使用RGB
coord_map("polyconic") + #指定投影方式为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)
)
7*、计算经纬度平均值添加标签
midpos <- function(x) mean(range(x,na.rm=TRUE)) #取形状内的平均坐标 centres <- ddply(china_data,.(province),colwise(midpos,.(long,lat))) ggplot(china_data,aes(long,lat))+ #此处语法与前面不同,参考ggplot2一书P85 geom_polygon(aes(group=group,fill=zhibiao),colour="black")+ scale_fill_gradient(low="white",high="steelblue") + coord_map("polyconic") + geom_text(aes(label=province),data=centres) + theme( panel.grid = element_blank(), panel.background = element_blank(), axis.text = element_blank(), axis.ticks = element_blank(), axis.title = element_blank() )
8*、读取省会城市坐标添加标签
province_city <- read.csv("D:/Astatistics/R/画热力图数据材料/省会坐标.csv") #读取省会城市坐标 ggplot(china_data,aes(long,lat))+ geom_polygon(aes(group=group,fill=zhibiao),colour="grey60")+ scale_fill_gradient(low="white",high="steelblue") + coord_map("polyconic") + geom_text(aes(x = jd,y = wd,label = province), data =province_city)+ theme( panel.grid = element_blank(), panel.background = element_blank(), axis.text = element_blank(), axis.ticks = element_blank(), axis.title = element_blank() )
时间: 2024-10-27 20:55:37