【问题标题】:Matplotlib - Changing line color above/below hlineMatplotlib - 在 hline 上方/下方更改线条颜色
【发布时间】:2018-02-23 02:14:24
【问题描述】:

我有一个线图和 2 条线,都使用不同的颜色,我正在用线的颜色填充主线与线交叉的区域。除此之外,我想对这些区域的主线使用相同的颜色。简而言之,当前输出:

期望的输出:

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

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)

【问题讨论】:

    标签: python-2.7 matplotlib


    【解决方案1】:

    原则上,您可以将绘图分为三部分,upper 以上的值、lower 以下的值和中间的值。从这个意义上说,这个问题已经被问到并得到了回答,例如

    如果您的点密度足够高,那么这些解决方案会非常有效,这样线最终会足够接近阈值线。

    在您有较大差距的情况下,它们可能不太适合。因此,我将在这里给出一个解决方案,它会插入间隙以使线条恰好在阈值线处结束。

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

    【讨论】:

    • 有一个小问题,线在穿过下水平线的点上仍然是蓝色的,但是通过简单地在蓝线 之后绘制水平线很容易解决这个问题。除此之外,完美解决,谢谢。
    • 这基本上也是我采用的方法。我有时间序列数据,所以在 pandas 中,我可以轻松地使用 .resample('S').interpolate() 使点足够密集以超过阈值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-04
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-05
    • 2020-06-16
    相关资源
    最近更新 更多