使用python 绘制中国人口热气图

使用 python matlib 绘制热力图

绘制世界地图

点击查看代码
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

plt.figure(figsize=(16,8))
m = Basemap()
m.drawcoastlines()

plt.show()

绘制国家轮廓

点击查看代码
 m.drawcountries(linewidth=1.5)
直接定位到中国版图
点击查看代码
m = Basemap(llcrnrlon=73, llcrnrlat=18, urcrnrlon=135, urcrnrlat=53)

添加兰博投影效果

点击查看代码
m = Basemap(llcrnrlon=77, llcrnrlat=14, urcrnrlon=140, urcrnrlat=51, projection='lcc', lat_1=33, lat_2=45, lon_0=100)

绘制中国省份 需要下载中国经纬度 csv

点击查看代码
m.readshapefile('CHN_adm_shp/CHN_adm1', 'states', drawbounds=True)

先给中国地图上色

  • gca :Get Current Axes 获得当前图形的座标轴
  • facecolor ='r' r= red
点击查看代码
from matplotlib.patches import Polygon

ax = plt.gca() 
for nshape, seg in enumerate(m.states):
    poly = Polygon(seg, facecolor='r')
    ax.add_patch(poly)

添加人口人力热力效果

增加调色板基准色

点击查看代码
cmap = plt.cm.YlOrRd

调整每个省份的颜色

点击查看代码
colors[s] = cmap(np.sqrt((pop - vmin) / (vmax - vmin)))[:3]

将颜色绘制到地图

点击查看代码
color = rgb2hex(colors[statenames[nshape]]) poly = Polygon(seg, facecolor=color, edgecolor=color)

一下完整代码

点击查看代码
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib.patches import Polygon
from matplotlib.colors import rgb2hex
import numpy as np
import pandas as pd

plt.figure(figsize=(16, 8))
m = Basemap(
    llcrnrlon=77,
    llcrnrlat=14,
    urcrnrlon=140,
    urcrnrlat=51,
    projection='lcc',
    lat_1=33,
    lat_2=45,
    lon_0=100
)
m.drawcountries(linewidth=1.5)
m.drawcoastlines()

m.readshapefile('CHN_adm_shp/CHN_adm1', 'states', drawbounds=True)

df = pd.read_csv('pop.csv')
df['省名'] = df.地区
df.set_index('省名', inplace=True)

colors = {}
provinces = []
for shape_dict in m.states_info:
    name = shape_dict['NL_NAME_1']
    p = name.split('|')
    s = p[1] if len(p) > 1 else p[0]
    provinces.append(s)
    pop = df['人口数'][s]
    colors[s] = plt.cm.YlOrRd(np.sqrt((pop - 3000000) / (100000000 - 3000000)))[:3]

ax = plt.gca()
for n_shape, seg in enumerate(m.states):
    color = rgb2hex(colors[provinces[n_shape]])
    poly = Polygon(seg, facecolor=color, edgecolor=color)
    ax.add_patch(poly)

if __name__ == '__main__':
    plt.show()

代码 码云

参考: https://segmentfault.com/a/1190000010871928

posted @ 2022-10-28 15:40  vx_guanchaoguo0  阅读(362)  评论(0编辑  收藏  举报