fill_between with matplotlib and a where condition of two lists

前端 未结 1 1749
抹茶落季
抹茶落季 2021-01-25 06:38

I am trying to shade the area before the point of intersection of the two curves produced by this example code:

import numpy as np
import matplotlib.pyplot as pl         


        
相关标签:
1条回答
  • 2021-01-25 06:55

    You are completely right, you need to interpolate. And that is ludicrously complicated, as you need to add the interpolate=True keyword argument to the call to fill_between.

    ax.fill_between(x,y1,y2,where=z1>=z2,color='grey', interpolate=True)
    

    Complete code to reproduce:

    import numpy as np
    import matplotlib.pyplot as plt 
    
    x = np.arange(0,100,10)
    y1 = [0,2,4,6,8,5,4,3,2,1]
    y2 = [0,1,3,5,6,8,9,12,13,14]
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(x,y1,linestyle='-')
    ax.plot(x,y2,linestyle='--')
    
    z1 = np.array(y1)
    z2 = np.array(y2)
    
    ax.fill_between(x,y1,y2,where=z1>=z2,color='grey',alpha=0.5, interpolate=True)
    
    plt.show()  
    
    0 讨论(0)
提交回复
热议问题