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

如何在Matplotlib产能图表中仅为指定周显示红色延迟单元条形图

产能图表(Capacity Chart)问题解决

问题描述

制作生产用产能图表,包含三类数据:

  • 黄色条形:固定值的Plan value(计划值)
  • 绿色条形:Current value(当前值),即当期生产数量
  • 红色条形:Late units(延迟单元),例如第45周生产的10个单元本该属于第44周,需标记为红色

原代码会在所有周显示红色条形,修改后虽能仅在第45周显示红色条形,但丢失了周数标签,需实现:仅在需要的周显示第三个条形,同时保留所有周数标签。

原代码

import matplotlib.pyplot as plt
import numpy as np

plt.figure('Capacity chart 2023')

# create data
x = [42,43,44,45]
y1 = np.array(300) # plan
y2 = np.array([172, 132, 189, 62]) # fact
y3 = np.array(10) # late

# plot bars in stack manner
plt.bar(x, y1, color='yellow', align="center", tick_label=x) # plan
plt.bar(x, y2, color='green', align="center", tick_label=x) # fact
plt.bar(x, y3, color='red', align="center", tick_label=x) # late

ax = plt.gca()
for container in ax.containers:
    plt.bar_label(container)

plt.title('Capacity chart 2023')
plt.ylabel('Units amount')
plt.xlabel('Week number')
plt.legend(["Plan value", "Current value", "Late units"], loc="upper right")
plt.get_current_fig_manager().window.state('zoomed')

plt.show()

尝试修改的问题代码片段

i = [45,45,45,45]
plt.bar(i, y3, color='red', align="center", tick_label=x) # late

修改后仅第45周显示红色条形,但丢失了周数标签。

解决方案

核心思路:让延迟单元数组y3仅在需要显示的周对应位置设置数值,其余周设为0,这样红色条形仅在目标周显示,同时保留原x轴的周数标签。

修改后的完整代码

import matplotlib.pyplot as plt
import numpy as np

plt.figure('Capacity chart 2023')

# create data
x = [42,43,44,45]
y1 = np.array(300) # plan(固定值,自动广播为与x长度一致的数组)
y2 = np.array([172, 132, 189, 62]) # fact
y3 = np.array([0, 0, 0, 10]) # late:仅第45周有10个延迟单元,其余周为0

# plot bars:保持x轴为所有周数,仅y3对应位置有值
plt.bar(x, y1, color='yellow', align="center", tick_label=x) # plan
plt.bar(x, y2, color='green', align="center") # fact:无需重复设置tick_label
plt.bar(x, y3, color='red', align="center") # late:无需重复设置tick_label

ax = plt.gca()
for container in ax.containers:
    plt.bar_label(container)

plt.title('Capacity chart 2023')
plt.ylabel('Units amount')
plt.xlabel('Week number')
plt.legend(["Plan value", "Current value", "Late units"], loc="upper right")
plt.get_current_fig_manager().window.state('zoomed')

plt.show()

关键说明

  1. 调整延迟数据数组:将y3改为[0,0,0,10],仅目标周(第45周)保留数值,其余周设为0,这样红色条形仅在该周显示,其他周因高度为0不会渲染。
  2. 避免重复设置tick_label:仅在第一个plt.bar中设置tick_label=x即可,后续重复设置会覆盖x轴刻度,导致标签异常。
  3. 保留原x轴坐标:保持x为所有周数[42,43,44,45],确保x轴始终显示全部周数标签。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 12:08:14