python 2.7 - Matplotlib - Changing line color above/below hline -


i have line plot , 2 hlines, using different colors, , i'm filling areas main line crosses hlines color of hline. in addition that, i'd use same color main line in areas. in nutshell, current output: enter image description here

desired output: enter image description here

and relevant code i'm using:

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) 

in principle may split plot 3 parts, values above upper, values below lower , values in middle. in sense question has been asked , answered, e.g.

those solutions work great if point density high enough, such lines end close enough threshold line.

in case have larger gaps not suited. hence give solution here, interpolates gaps such lines end @ threshold line.

import numpy np; np.random.seed(43) import matplotlib.pyplot 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]     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


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -