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

Matplotlib折线图指定分位数区域填充失效问题求助

解决Matplotlib分位数区间填充失效的问题

我来帮你修复这个折线图区间填充的问题!你的代码里有两个关键问题导致后续区间没显示填充效果,咱们一步步解决:

问题分析

  1. 数组长度不匹配:你的testx有5个元素,但testy有6个,这会导致绘图时的潜在错误(甚至直接报错),而且会让fill_between的逻辑混乱。
  2. where条件的逻辑缺陷:对于离散的x点,fill_between的where条件需要覆盖区间内的连续线段,而不仅仅是单个点。比如你第二个区间的(testx > 0.25) & (testx <= 0.5),在原testx里只有0.5这一个点满足,相邻的前一个点0.25不满足,所以这段线段不会被填充。

修正后的完整代码

import numpy as np
import matplotlib.pyplot as plt

# 第一步:修正数组长度,确保每个分位数端点对应一个时间值
testx = np.array([0.0, 0.05, 0.25, 0.5, 0.9, 1.0])  # 补充1.0作为最大分位数端点
testy = np.array([0, 5, 14.75, 40, 96.1, 120])

plt.plot(testx, testy, color='darkblue', linewidth=2)  # 绘制基础折线

# 填充各个分位数区间,用不同颜色区分,alpha参数控制透明度
# 区间1:≤0.25
plt.fill_between(testx, testy, where=(testx <= 0.25), color='skyblue', alpha=0.3)

# 区间2:>0.25 且 ≤0.5(调整条件覆盖线段)
plt.fill_between(testx, testy, where=(testx >= 0.25) & (testx <= 0.5), color='lightgreen', alpha=0.3)

# 区间3:>0.5 且 ≤0.9
plt.fill_between(testx, testy, where=(testx > 0.5) & (testx <= 0.9), color='salmon', alpha=0.3)

# 区间4:>0.9
plt.fill_between(testx, testy, where=(testx > 0.9), color='gold', alpha=0.3)

# 添加图表标注,提升可读性
plt.xlabel('Percentiles', fontsize=12)
plt.ylabel('Time (seconds)', fontsize=12)
plt.title('Percentile vs. Time with Interval Fills', fontsize=14)

plt.show()

关键优化点说明

  • 数组对齐:补充1.0作为分位数的最大端点,让testx和testy长度完全匹配,确保每个x值对应唯一的y值。
  • where条件调整:对于第二个区间,我们把条件改为(testx >= 0.25) & (testx <= 0.5),这样0.25和0.5两个端点都满足条件,fill_between就会填充这两个点之间的线段区域,完美覆盖你想要的>0.25且≤0.5区间。
  • 视觉优化:用不同颜色区分区间,添加alpha参数让填充半透明,既突出区间又不会遮挡折线本身。

如果你更倾向于直接提取区间片段来填充(逻辑更直观),也可以用这种方式:

# 提取区间>0.25且≤0.5的x、y片段
x_segment = testx[(testx >= 0.25) & (testx <= 0.5)]
y_segment = testy[(testx >= 0.25) & (testx <= 0.5)]
plt.fill_between(x_segment, y_segment, color='lightgreen', alpha=0.3)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 03:58:28