使用Python绘制不等块宽热力图/堆叠条形图实现路段速度可视化
解决方案思路
直接用matplotlib的自定义矩形块逐段绘制,避开seaborn封装函数的自动排序逻辑,既可以保留路段原始顺序,也能实现宽度随路段长度动态调整的效果。
可运行完整代码
import pandas as pd import matplotlib.pyplot as plt from matplotlib.patches import Rectangle from matplotlib.colors import Normalize import matplotlib.cm as cm # 样例数据 d = {'timeRanges': ['00:00-06:30', '00:00-06:30', '00:00-06:30', '00:00-06:30', '07:00-15:00', '07:00-15:00', '07:00-15:00', '07:00-15:00', '16:00-17:30', '16:00-17:30', '16:00-17:30', '16:00-17:30'], 'segmentOrder': [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3], 'segmentDistance': [20, 45, 60, 30, 20, 45, 60, 30, 20, 45, 60, 30], 'distanceAlongRoute': [20, 65, 125, 155, 20, 65, 125, 155, 20, 65, 125, 155], 'averageSpeed': [54.2, 48.1, 23.5, 33.7, 56.2, 53.2, 42.5, 44.2, 50.2, 46.2, 35.3, 33.2]} df = pd.DataFrame(data=d) # 绘图配置参数,可按需调整 ROW_HEIGHT = 1 # 每个时间段行的高度 Y_GAP = 0.2 # 行间距 # 配色:红对应低速、黄对应中速、绿对应高速 CMAP = cm.get_cmap('RdYlGn') # 提取时间段(保留原始顺序) time_ranges = df['timeRanges'].unique() # 速度值归一化,用于颜色映射 norm = Normalize(vmin=df['averageSpeed'].min(), vmax=df['averageSpeed'].max()) # 创建画布 fig, ax = plt.subplots(figsize=(12, len(time_ranges)*1.5)) # 逐行逐段绘制热力块 for row_idx, tr in enumerate(time_ranges): # 按segmentOrder排序,严格保证路段原始顺序 segment_df = df[df['timeRanges'] == tr].sort_values('segmentOrder').reset_index(drop=True) y_start = row_idx * (ROW_HEIGHT + Y_GAP) x_start = 0 for _, seg in segment_df.iterrows(): seg_width = seg['segmentDistance'] # 按速度取对应颜色 color = CMAP(norm(seg['averageSpeed'])) # 绘制矩形块,白色边框区分路段 rect = Rectangle((x_start, y_start), seg_width, ROW_HEIGHT, color=color, ec='white', lw=1) ax.add_patch(rect) x_start += seg_width # 调整坐标轴样式 ax.set_xlim(0, df['distanceAlongRoute'].max()) ax.set_ylim(0, len(time_ranges)*(ROW_HEIGHT + Y_GAP)) ax.set_yticks([i*(ROW_HEIGHT + Y_GAP) + ROW_HEIGHT/2 for i in range(len(time_ranges))]) ax.set_yticklabels(time_ranges) ax.set_xlabel('路线累计里程') # 添加速度颜色条 sm = cm.ScalarMappable(norm=norm, cmap=CMAP) sm.set_array([]) cbar = fig.colorbar(sm, ax=ax) cbar.set_label('平均速度') plt.tight_layout() plt.show()
效果说明
- 路段严格按
segmentOrder原始顺序排列,不会被自动重排 - 每个热力块的宽度完全匹配对应路段的实际长度
- 颜色映射符合需求:绿色对应高速、黄色对应中速、红色对应低速
- 每一行对应一个时间段,和TomTom Move的展示逻辑一致
- 可通过修改开头的配置参数调整行高、间距、配色等样式
内容的提问来源于stack exchange,提问作者dyrjohn
相关产品推荐
相关产品推荐

