本人电脑win10,python3.6.5, 32位 。安装出现问题可参考神农尝百草的博客https://blog.csdn.net/moxigandashu/article/details/68945845
下载basemap地址链接https://www.lfd.uci.edu/~gohlke/pythonlibs/,ctrl + f 迅速找到basemap安装包
不过安装 basemap 之前要安装pyproj
由于我的python是3.6版本32位,所以我选择下载: pyproj‑1.9.5.1‑cp36‑cp36m‑win32.whl和
basemap‑1.2.0‑cp36‑cp36m‑win32.whl。
然后pip 安装
#一定要注意先后顺序,不然会出错
pip install pyproj‑1.9.5.1‑cp36‑cp36m‑win32.whl
pip install basemap‑1.2.0‑cp36‑cp36m‑win32.whl
在[https://gadm.org/download_country_v3.html]上下载中国和台湾的地图包
下载之后解压shapefile文件。
国家统计局网站:[http://www.stats.gov.cn/tjsj/pcsj/rkpc/6rp/indexce.htm]
下载第一个就行:
下载好的数据需要处理一下:
import pandas as pd
df = pd.read_excel(r'C:\Users\Administrator\Downloads\A0101a.xls', encoding='utf-8', head=None, skiprows=6)
df.head()
df[['省份', '人口数']]= df[['Unnamed: 0', 'Unnamed: 4']]
df = df['省份'].to_frame().join(df['人口数'])
df = df[1:]
df['省名'] = df['省份'].str.replace(' ', '')
df.set_index('省名', inplace = True)
del df['省份']
df.to_csv('chnpop.csv')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib.patches import Polygon
from matplotlib.colors import rgb2hex
from matplotlib.collections import PatchCollection
from matplotlib import pylab
plt.figure(figsize = (10,5))
# m= Basemap(llcrnrlon=73, llcrnrlat=18, urcrnrlon=135, urcrnrlat=55) #指定中国的经纬度
m= Basemap(llcrnrlon=77, llcrnrlat=14, urcrnrlon=140, urcrnrlat=51, \
projection='lcc', lat_1=33, lat_2=45, lon_0=100) # ‘lcc'将投影方式设置为兰伯特投影
# projection='ortho' 投影方式设置为正投影——类似地球仪
m.readshapefile(r'E:\Project\data\gadm36_CHN_shp\gadm36_CHN_1', 'states', drawbounds = True)
#读取数据
df = pd.read_csv('chnpop.csv')
df['省名'] = df.省名.str[:2]
df.set_index('省名', inplace=True)
# 把每个省的数据映射到colormap上
statenames=[]
colors={}
patches = []
cmap = plt.cm.YlOrRd # 国旗色红黄色调
vmax = 10**8
vmin = 3*10**6
# 处理地图包里的省名
for shapedict in m.states_info:
statename = shapedict['NL_NAME_1']
p = statename.split('|')
if len(p) > 1:
s = p[1]
else:
s = p[0]
s = s[:2]
if s == '黑龍':
s = '黑龙'
statenames.append(s)
pop = df['人口数'][s]
colors[s] = cmap(np.sqrt((pop - vmin) / (vmax - vmin)))[:3] #根据归一化后的人口数映射颜色
ax = plt.gca()
for nshape, seg in enumerate(m.states):
color = rgb2hex(colors[statenames[nshape]])
poly = Polygon(seg, facecolor=color, edgecolor=color)
patches.append(poly)
ax.add_patch(poly)
# 图片绘制加上台湾(台湾不可或缺)
m.readshapefile(r'E:\Project\data\gadm36_TWN_shp\gadm36_TWN_1', 'taiwan', drawbounds=True)
for nshape, seg in enumerate(m.taiwan):
poly = Polygon(seg, facecolor='w')
patches.append(poly)
ax.add_patch(poly)
# 添加colorbar 渐变色legend
colors1 = [i[1] for i in colors.values()]
colorVotes = plt.cm.YlOrRd
p = PatchCollection(patches, cmap =colorVotes)
p.set_array(np.array(colors1))
pylab.colorbar(p)
#m.drawcoastlines() #绘制海岸线
#m.drawcountries(linewidth=1.5) #绘制国家边界线
plt.show()