You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Matplotlib创建按检查状态着色的单条目方块水平条形图

实现每个检查项独立着色的水平条形图解决方案

你当前的代码是按每日状态总数生成堆叠色块,无法体现单个检查项的独立状态。要实现每个检查项以独立方块呈现并按状态着色,需调整数据组织方式,逐个绘制每个检查项对应的小条形。

解决方案步骤

  • 重新组织数据:不再统计每日0/1的总数,而是保留每一天的所有检查项状态列表,精准定位每个检查项的位置和颜色。
  • 逐个绘制小方块:对每一天的每个检查项,绘制宽度为1的水平小条形,根据状态设置颜色(0=绿色,1=红色),并依次排列在对应天数的水平位置上。
  • 调整坐标轴样式:优化y轴刻度位置,确保每条对应一天,x轴显示检查项的序号。

完整实现代码

import matplotlib.pyplot as plt

def generate_graph(day_check):
    # 按天存储每个检查项的状态列表
    daily_data = {}
    for timestamp, status in day_check:
        day = timestamp.split('-')[2].split(' ')[0]
        if day not in daily_data:
            daily_data[day] = []
        daily_data[day].append(status)
    
    # 整理天数顺序,反转后让最早的天在下方
    days = list(daily_data.keys())
    days.reverse()
    # 确定最大检查项数量,用于设置x轴范围
    max_checks = max(len(states) for states in daily_data.values())
    
    fig, ax = plt.subplots(figsize=(10, 8))
    # 设置每个条形的高度(天之间的间距)
    bar_height = 0.8
    
    # 遍历每一天,绘制每个检查项的小方块
    for y_idx, day in enumerate(days):
        states = daily_data[day]
        for x_idx, status in enumerate(states):
            # 根据状态设置颜色
            color = 'green' if status == '0' else 'red'
            # 绘制单个小条形:x位置是x_idx,y位置是y_idx,宽度1,高度bar_height
            ax.barh(y_idx, 1, height=bar_height, left=x_idx, color=color)
    
    # 设置y轴刻度和标签
    ax.set_yticks(range(len(days)))
    ax.set_yticklabels(days)
    # 设置x轴刻度,从0到最大检查项数
    ax.set_xticks(range(max_checks + 1))
    ax.set_xlabel('检查项序号')
    ax.set_ylabel('日期')
    
    # 添加图例
    from matplotlib.patches import Patch
    legend_elements = [Patch(facecolor='green', label='成功(状态0)'),
                       Patch(facecolor='red', label='错误(状态1)')]
    ax.legend(handles=legend_elements)
    
    plt.tight_layout()
    plt.savefig('graph.png')

# 测试数据
day_check_data = [
    ("2023-01-01 12:30:00", '0'),
    ("2023-01-02 14:45:00", '1'),
    ("2023-01-03 10:15:00", '0'),
    ("2023-02-03 12:30:00", '1'),
    ("2023-02-04 14:45:00", '0'),
    ("2023-02-05 10:15:00", '1'),
    ("2023-03-05 12:30:00", '0'),
    ("2023-03-06 14:45:00", '1'),
    ("2023-03-07 10:15:00", '0'),
    ("2023-04-07 12:30:00", '1'),
    ("2023-04-08 14:45:00", '0'),
    ("2023-04-09 10:15:00", '1'),
]

generate_graph(day_check_data)

关键逻辑说明

  • 数据组织:daily_data存储每个日期对应的所有检查项状态列表,而非统计总数,确保能获取每个检查项的具体状态。
  • 逐个绘制:通过两层循环,外层遍历日期,内层遍历该日期的每个检查项,用barh绘制宽度为1的小条形,left=x_idx保证方块依次排列。
  • 图例设置:使用Patch手动创建图例,适配单个小条形无独立标签的场景,更灵活直观。

内容的提问来源于stack exchange,提问作者Giuseppe Debby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 00:03:18