得到杭州每个行政区在早高峰时期、晚高峰时期的出发量,想要在行政区上根据颜色的深浅图示出发量的多少。
1.寻找杭州行政区的shapefile文件,并能被python读取
2.在杭州行政区上,用颜色深浅表示各个行政区在早高峰、晚高峰时期出发量的多少
一、查找杭州行政区shapefile文件并由python读取
查找杭州市行政区shapefile文件的见上篇文章
https://blog.csdn.net/yianxiang17hao/article/details/118810876?spm=1001.2014.3001.5501
二、python绘图
step1:读取底图
# 一、读取底图
# 1.导入需要的包
#geopandas包
import geopandas
#shapely包
from shapely.geometry import Point,Polygon,shape
shp = r'文件路径/XX.shp'
hz = geopandas.GeoDataFrame.from_file(shp,encoding = 'utf-8')
hz.plot()
得到底图如下:
step2:读取数据文件
# 二、读取数据
# 1. 导入包
import pandas as pd
# 2.从excel读取数据
#文件路径
file_path = r'文件路径\XX.xlsx'
#读取sheet的名字
sheetName = 'XX'
morning_data = pd.read_excel(file_path,sheet_name=sheetName)
查看moning_data 和 hz的数据格式
step3: 任务是把hz表格里的geometry按照name添加到morning_data表格
hz = hz.sort_values(by='name')
morning_data = morning_data.sort_values(by='name')
geometry = []
for i in range(0,len(hz)):
geometry.append(hz['geometry'].iloc[i])
morning_data['geometry'] = geometry
morning_data
结果:
step4: 把morning_data转换成geodataframe形式
morning_data = geopandas.GeoDataFrame(morning_data)
step5: 画图
import matplotlib.pyplot as plt
fig = plt.figure(1,(10,8),dpi = 250)
ax = plt.subplot(111)
plt.sca(ax)
#设置colormap的数据
import matplotlib as mpl
import matplotlib
vmax = max(morning_data['cnt'])
vmin = min(morning_data['cnt'])
#设定一个标准化的工具,设定OD的colormap最大最小值,他的作用是norm(count)就会将count标准化到0-1的范围内
norm = mpl.colors.Normalize(vmin=vmin,vmax=vmax)
#设定colormap的颜色
cmapname = 'Reds'
#cmap是一个获取颜色的工具,cmap(a)会返回颜色,其中a是0-1之间的值
cmap = matplotlib.cm.get_cmap(cmapname)
#绘制密度图
for i in range(0,len(morning_data)):
district = morning_data['name'].iloc[i]
district_draw = morning_data[morning_data['name'] == district]
#设定第i个行政区的颜色
color_i=cmap(norm(district_draw['cnt'].iloc[0]))
color_i = color_i[:3] + (0.9,)
#绘制行政区划
district_draw.plot(ax = ax,edgecolor = (0,0,0,1),facecolor = color_i,linewidths=0.5)
# 绘制假的colorbar,这是因为,我们画的OD是线,没办法直接画出来colorbar
# 所以我们在一个看不见的地方画了一个叫imshow的东西,他的范围是0到vmax
#然后我们再对imshow添加colorbar
plt.imshow([[vmin,vmax]], cmap=cmap)
#设定colorbar的大小和位置
cax = plt.axes([0.15, 0.4, 0.02, 0.3])
plt.colorbar(cax=cax)
#然后要把镜头调整回到杭州地图那,不然镜头就在imshow那里了
ax.set_xlim(118.2,120.9)
ax.set_ylim(29.0,30.8)
plt.axis('off')
plt.show()
结果
同理获得晚高峰时期: