最近在网上找了几种画中国地图方法,最终觉得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数据下载:
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)]))