【问题标题】:matplotlib: Why is my multi-colored line plot ignoring boundary values?matplotlib:为什么我的多色线图忽略了边界值?
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 不错。之前没见过set_clip_path。
  • 不错。与宣传的完全一样,只是我必须调整下部线的linewidth 参数,以使基础线不会达到峰值。
  • @rocksNwaves 您还可以扩展这个想法,添加一个从thresh 到x.max() 的poly_over,并使用它来剪辑line_over。
猜你喜欢
  • 1970-01-01
  • 2013-09-30
  • 2016-06-20
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 2011-12-31
  • 2014-01-12
相关资源
最近更新 更多