【发布时间】:2020-12-21 16:42:21
【问题描述】:
我有一个异常阈值,在我的情节中由 axhline 注释。我希望添加标记和/或更改高于此阈值的线的颜色。我遵循了以下 matplotlib 教程:
https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/multicolored_line.html
除了在 SO 上使用了这个问题/答案:
How to plot multi-color line if x-axis is date time index of pandas
制作这个情节:
这看起来不错,直到您放大数据的子集:
不幸的是,这个解决方案似乎不适用于我的目的。我不确定这是否是我的错误,但显然这些线在阈值以下是红色的。在我看来,另一个问题是代码是多么的笨拙和冗长:
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()
dates 和scores 和thresh 生成这里没有显示,但可以用随机数重新生成以使此代码运行
问题:
为什么我的图表中的红线有时会低于阈值?有没有办法缩短为此目的所需的代码量?
【问题讨论】:
-
您需要将与水平线的交点包含在绘制的曲线中。这些更改显然会使代码“更加笨拙”。如果您想要更简单的代码,而不是更改曲线的颜色,您可以通过
ax.axhspan()更改背景颜色。 -
@JohanC,这是个好主意,谢谢。我也看到这样做了。我试试看!
标签: python matplotlib seaborn