Matplotlib - 更改线条上方/下方的线条颜色

2023-11-23

I have a line plot and 2 hlines, all using different colors, and I'm filling the areas where the main line crosses the hlines with the color of the hline. In addition to that, I'd like to use the same color for the main line in those areas. In a nutshell, current output: enter image description here

Desired output: enter image description here

以及我当前正在使用的相关代码:

lower, upper = 20, 80

self.indicatorPlot.axhline(lower, color="red")
self.indicatorPlot.axhline(upper, color="green")

self.indicatorPlot.plot(self.chartTimes, self.indicatorData, color="blue")

self.indicatorPlot.fill_between(self.chartTimes, self.indicatorData, lower, where=(self.indicatorData <= lower), facecolor="red", interpolate=True)
self.indicatorPlot.fill_between(self.chartTimes, self.indicatorData, upper, where=(self.indicatorData >= upper), facecolor="green", interpolate=True)

原则上你可以将你的图分成三个部分,上面的值upper,下面的值lower以及中间的值。从这个意义上说,这个问题已经被提出并回答了,例如

  • Python:如果超出特定范围,是否可以更改图中的线条颜色?
  • 情节:颜色都大于不同的颜色

如果您的点密度足够高,使得线条最终足够接近阈值线,那么这些解决方案效果很好。

如果间隙较大,它们可能不太适合。因此,我将在这里给出一个解决方案,该解决方案对间隙进行插值,以使线条恰好在阈值线处结束。

import numpy as np; np.random.seed(43)
import matplotlib.pyplot as plt

t = np.linspace(0,100,301)
x = np.cumsum(np.random.randn(len(t)))

lower,upper = 0,8

fig, ax=plt.subplots()

ax.axhline(lower, color="crimson")
ax.axhline(upper, color="limegreen")


def insertzeros(t, x, zero=0):
    ta = []
    positive = (x-zero) > 0
    ti = np.where(np.bitwise_xor(positive[1:], positive[:-1]))[0]
    for i in ti:
        y_ = np.sort(x[i:i+2])
        z_ = t[i:i+2][np.argsort(x[i:i+2])]
        t_ = np.interp(zero, y_, z_)
        ta.append( t_ )
    tnew = np.append( t, np.array(ta) )
    xnew = np.append( x, np.ones(len(ta))*zero )
    xnew = xnew[tnew.argsort()]
    tnew = np.sort(tnew)
    return tnew, xnew

t1,x1 = insertzeros(t,x, zero=lower)
t1,x1 = insertzeros(t1,x1, zero=upper)

xm = np.copy(x1)
xm[(x1 < lower) | (x1 > upper)] = np.nan        
ax.plot(t1,xm, color="C0")

xl = np.copy(x1)
xl[(x1 > lower)] = np.nan        
ax.plot(t1,xl, color="crimson")
#
xu = np.copy(x1)
xu[(xu < upper)] = np.nan        
ax.plot(t1,xu, color="limegreen")

ax.fill_between(t, x, lower, where=(x <= lower), facecolor="crimson", interpolate=True, alpha=0.5)
ax.fill_between(t, x, upper, where=(x >= upper), facecolor="limegreen", interpolate=True, alpha=0.5)


plt.show()

enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Matplotlib - 更改线条上方/下方的线条颜色 的相关文章

随机推荐