很多時候我們需要表示不同地區(qū)的某個值岸霹,那表示的方法有兩種躁锁,第一種是地圖+熱力圖纷铣,用地圖上的顏色表示值得大小,另一種是地圖+氣泡圖战转,用氣泡大小來表示值搜立,當然顏色也可以表示其他參數(shù)。
本篇主要講解地圖+氣泡圖如何畫出
數(shù)據(jù)準備:
1槐秧、地圖所需數(shù)據(jù):全國地圖GIS文件
2啄踊、氣泡圖所需數(shù)據(jù):城市名稱忧设,經(jīng)度,維度颠通,具體數(shù)值址晕,如圖
實現(xiàn)原理:
將圖分解開來,發(fā)現(xiàn)是地圖+氣泡圖顿锰,我們需要畫出地圖谨垃。那如何講氣泡圖展示在地圖上呢,將位置對應到地圖上的x,y軸硼控,也就是經(jīng)度和維度刘陶,然后就可完美的畫圖地圖了
R代碼:
#chinamap
setwd("C:\\Users\\a\\Desktop")
library(gpclib)
library(ggplot2)
library(maps)
library(maptools)
#讀取各省的邊界數(shù)據(jù)等
shape <- readShapePoly("socialbeta/china-province-border-data/bou2_4p.shp")
#轉化數(shù)據(jù)格式,可以用fortify()函數(shù)替代
shape@data$id <- rownames(shape@data)
shape.fort <- fortify(shape, region='id')
shape.fort<-shape.fort[order(shape.fort$order), ]
#獲取氣泡圖數(shù)據(jù)
city<-read.csv('大眾點評杭州民宿用戶畫像.csv')
#建立函數(shù)牢撼,將背景全部取消
theme_clean <- function(base_size=12){
require(grid)
theme_grey(base_size)
theme(
axis.title = element_blank(),
axis.text = element_blank(),
panel.background = element_blank(),
panel.grid = element_blank(),
axis.ticks.length = unit(0, "cm"),
axis.ticks.margin = unit(0, "cm"),
panel.margin = unit(0, "lines"),
plot.margin = unit(c(0,0,0,0), "lines"),
complete = TRUE
)
}
#畫圖地圖+氣泡圖
mymap = ggplot(data = shape.fort) +
geom_polygon(aes(x = long, y = lat, group = group), colour = "grey",fill='white')
mymap2<-mymap + coord_map()+geom_point(data=city,aes(x=經(jīng)度,y=維度,size=人數(shù),color=地域))
#添加標簽匙隔,取消圖例(因為圖例太長。熏版。)牡直,保存圖片
map<-mymap2
+ theme_clean()+theme(legend.position='none')+geom_text(data =city,
aes(x=經(jīng)度,y=維度,label =地域),vjust=-0.5,hjust=-1,size=1.5)
ggsave('map.png',map)
最終效果,由于數(shù)據(jù)相差較大纳决,且集中在江浙滬碰逸,故其他地區(qū)的氣泡較小