如何用颜色图绘制序列分割结果?求Matplotlib示例代码
时序序列分割预测结果可视化示例
直接上符合需求的Matplotlib可视化代码,能直观对比真实标签与预测标签的差异,其中sit类固定用蓝色,其他类别自动分配不同颜色:
import matplotlib.pyplot as plt import numpy as np # 给定的标签列表 GroundTruth_List = ['sit', 'sit', 'sit', 'order_coco', 'order_coco', 'drink_coco'] Predicted_List = ['sit', 'sit', 'sit', 'order_coco', 'order_coco', 'drink_milk'] # 收集所有唯一标签,构建颜色映射 all_labels = list(set(GroundTruth_List + Predicted_List)) color_map = {} # 为'sit'指定蓝色 color_map['sit'] = '#1f77b4' # 为其他标签分配不同的颜色(使用matplotlib内置的tab10配色) other_labels = [label for label in all_labels if label != 'sit'] for idx, label in enumerate(other_labels): color_map[label] = plt.cm.tab10(idx % 10) # 时间轴(对应每1秒的索引) time_steps = np.arange(len(GroundTruth_List)) # 每个时间步的宽度设为1 step_width = 1 # 创建画布 fig, ax = plt.subplots(figsize=(10, 3)) # 绘制真实标签行(y=1的位置) for t, label in enumerate(GroundTruth_List): ax.add_patch(plt.Rectangle((t, 0.8), step_width, 0.4, color=color_map[label])) # 绘制预测标签行(y=0的位置) for t, label in enumerate(Predicted_List): ax.add_patch(plt.Rectangle((t, -0.2), step_width, 0.4, color=color_map[label])) # 设置轴属性 ax.set_xlim(-0.1, len(time_steps)) ax.set_ylim(-0.6, 1.4) ax.set_yticks([0, 1]) ax.set_yticklabels(['Predicted', 'Ground Truth']) ax.set_xlabel('Time (seconds)') ax.set_title('Sequence Segmentation Prediction vs Ground Truth') # 添加图例 handles = [plt.Rectangle((0,0),1,1, color=color_map[label]) for label in all_labels] ax.legend(handles, all_labels, bbox_to_anchor=(1.05, 1), loc='upper left') plt.tight_layout() plt.show()
代码说明:
- 颜色映射:手动将
sit设为蓝色,其余标签通过tab10配色循环自动分配不同颜色,保证类别区分度 - 可视化方式:用矩形色块代表每个时间步的标签,真实标签和预测标签分别在两条水平线上(对应y=1和y=0)
- 错误识别:最后1秒的
drink_coco(真实)和drink_milk(预测)颜色不同,能快速定位错误预测的位置
内容的提问来源于stack exchange,提问作者Jim Wang
相关产品推荐
相关产品推荐

