首页 > 解决方案 > matplotlib:为什么我的多色线图忽略了边界值?

问题描述

我有一个异常阈值,axhline在我的情节中用 an 注释。我希望添加标记和/或更改高于此阈值的线的颜色。我遵循了以下 matplotlib 教程:

https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/multicolored_line.html

以及这在 SO 上使用了这个问题/答案:

如果x轴是熊猫的日期时间索引,如何绘制多色线

要生成此图:

在此处输入图像描述

这看起来很不错,直到您放大数据的子集:

在此处输入图像描述

不幸的是,这个解决方案似乎不适用于我的目的。我不确定这是否是我的错误,但显然这些线在阈值以下是红色的。在我看来,另一个问题是代码多么笨拙和冗长:

import matplotlib.dates as mdates
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm

fig, ax = plt.subplots(figsize=(15,4))

inxval = mdates.date2num(dates.to_pydatetime())
points = np.array([inxval, scores]).T.reshape(-1,1,2)
segments = np.concatenate([points[:-1],points[1:]], axis=1)#[-366:]

cmap = ListedColormap(['b', 'r'])
norm = BoundaryNorm([0, thresh, 40], cmap.N)
lc = LineCollection(segments, cmap=cmap, norm=norm)

lc.set_array(scores)
ax.add_collection(lc)

monthFmt = mdates.DateFormatter("%Y")
ax.xaxis.set_major_formatter(monthFmt)
ax.xaxis.set_major_locator(mdates.YearLocator())

ax.autoscale_view()
# ax.axhline(y=thresh, linestyle='--', c='r')
plt.show()

datesand scores, and threshgeneration 在这里没有显示,但是可以用随机数重新生成以使此代码运行

问题:

为什么我的图表中的红线有时会低于阈值?有没有办法缩短为此目的所需的代码量?

标签: pythonmatplotlibseaborn

解决方案


一种选择是使用相同的数据绘制两条线,然后使用不可见的axhspan对象将其中一条线剪切到阈值以下:

f, ax = plt.subplots()
x = np.random.exponential(size=500)
line_over, = ax.plot(x, color="b")
line_under, = ax.plot(x, color="r")
poly = ax.axhspan(0, 1, color="none")
line_under.set_clip_path(poly)

在此处输入图像描述


推荐阅读