matplotlib:为什么我的多色折线图忽略边界值?

岩石

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

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

不仅如此,这里还使用了以下问题/答案:

如果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()

datesscores,以及thresh生成未在此处显示,但可以使用随机数重新生成以使此代码运行

题:

为什么图表中的红线有时会低于阈值?有没有一种方法可以简化为此目的所需的代码量?

姆瓦斯科姆

一种选择是用相同的数据绘制两条线,然后使用一个不可见的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)

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章