如何为Matplotlib stairs绘制的直方图填充不同颜色?
分区域着色直方图的实现方案
核心思路是将原直方图按指定分割点拆分为三个独立区间,分别调用plt.stairs绘制每个区间并设置不同填充色。关键是准确定位分割点在bins数组中的位置,从而拆分对应的统计数据。
完整代码示例
import numpy as np import matplotlib.pyplot as plt # 替换为你的实际数据 data = np.random.normal(loc=0, scale=2, size=1000) # 生成直方图的统计结果 counts, bins = np.histogram(data, bins=20) # 指定你需要的分割点x和y x = -1 y = 1 # 找到分割点在bins中的索引(right表示取分割点右侧的区间起始位置) idx_x = np.searchsorted(bins, x, side='right') idx_y = np.searchsorted(bins, y, side='right') # 拆分三个区域的统计数据和区间 # 左段:从左端到x left_counts = counts[:idx_x] left_bins = bins[:idx_x + 1] # 中段:x到y mid_counts = counts[idx_x:idx_y] mid_bins = bins[idx_x:idx_y + 1] # 右段:y到右端 right_counts = counts[idx_y:] right_bins = bins[idx_y:] # 分别绘制三个区域,设置不同填充色 plt.stairs(left_counts, left_bins, fill=True, color='skyblue', label='Left Region') plt.stairs(mid_counts, mid_bins, fill=True, color='salmon', label='Middle Region') plt.stairs(right_counts, right_bins, fill=True, color='lightgreen', label='Right Region') # 添加基础标注 plt.xlabel('Data Value') plt.ylabel('Frequency') plt.legend() plt.show()
关键细节说明
- 分割点定位:使用
np.searchsorted可以快速找到分割点在bins数组中的插入位置,确保拆分的区间准确对应分割点左右的区域。side='right'参数表示分割点落在区间右侧时,将其归为下一个区间的起始。 - 多图层叠加:
plt.stairs支持多次调用,后续绘制的区域会自动叠加在已有图层上,无需额外调整顺序。 - 自定义调整:如果需要更精细的区间控制,可以手动修改
bins数组,或者调整np.histogram的bins参数(比如指定固定区间)。
内容的提问来源于stack exchange,提问作者toto
相关产品推荐
相关产品推荐

