最近在網上找了幾種畫中國地圖方法,最終覺得R語言這個方法還是最適用的
1.用googlevis包,由於中國國情現在已經不能訪問google地圖了,所以大多中國用戶來說只能望洋興歎了。
2.用ggplot包,雖然也不錯是,但試了後還是些限制的,要用到的gpclib包,在windows和RedHat linux系統上是不被支持的,只有Ubuntu系統上支持,所以對於想在win和redhad linux畫圖不太容易。而且畫出來的地圖容易變形,不好調整。
3.最後還是plot工具畫的,看上還不錯,經過多方法參考和修改後,分享給大家。
library(maps)
library(mapdata)
library(maptools)
# 中國地圖
# map("china")
# 加載GIS數據
# GIS數據下載:http://cos.name/wp-content/uploads/2009/07/chinaprovinceborderdata_tar_gz.zip
x <- readShapePoly("bou2_4p.shp")
# 測試數據
# plot(x,col=gray(924:0/924));
# 定義地圖顏色函數
getColor <- function(mapdata,provname,provcol,othercol)
{ f=function(x,y) ifelse(x %in% y,which(y==x),0);
colIndex=sapply(iconv(x@data$NAME,"GBK","UTF-8"),f,provname);
col=c(othercol,provcol)[colIndex+1];
return(col);
}
# 測試數據
# provname=c("北京市","天津市","上海市","重慶市"); provcol=c("red","green","yellow","purple");
# provcol=c("red","green","yellow","purple");
# plot(x,col=getColor(x,provname,provcol,"white"));
# 查看省份名
# as.character(na.omit(unique(x@data$NAME)));
# 畫地圖數據
provname=c("北京市","天津市","河北省","山西省","內蒙古自治區", "遼寧省","吉林省","黑龍江省","上海市","江蘇省", "浙江省","安徽省","福建省","江西省","山東省", "河南省","湖北省","湖南省","廣東省", "廣西壯族自治區","海南省","重慶市","四川省","貴州省", "雲南省","西藏自治區","陝西省","甘肅省","青海省", "寧夏回族自治區","新疆維吾爾自治區","台灣省", "香港特別行政區");
pop <- c(1633,1115,6943,3393,2405,4298,2730,3824,1858,7625, 5060,6118,3581,4368,9367,9360,5699,6355,9449, 4768,845,2816,8127,3762,4514,284,3748,2617, 552,610,2095,2296,693);
# 構建圖例的位置
nf <- layout(matrix(c(1,1,1,1,1,2,1,1,1),3,3,byrow=TRUE), c(3,1), c(3,1), TRUE)
layout.show(nf)
#provcol <- rgb(red=1-pop/max(pop)/2,green=1-pop/max(pop)/2,blue=0);
#plot(x,col=getColor(x,provname,provcol,"white"),xlab="aaa",ylab="bbb");
provcol <- rgb(red=1-pop/max(pop)/1,green=1-pop/max(pop)/1,blue=1/1.5);
plot(x,col=getColor(x,provname,provcol,"white"),xlab="",ylab="")
## 整理數據
pop <- pop - min(pop)
pop=pop-min(pop)
# 添加圖例
par(mar=c(0,0,0,0))
par(mar=c(1,1,2,0),cex=0.5)
barplot(as.matrix(rep(1,31)),col=sort(provcol,dec=T),horiz=T,axes=F,border = NA )
axis(1,seq(1,32,by=3),sort(pop[seq(1,32,by=3)]))