Search code examples
pythonmatplotlibplotfill

Matplotlib: Argument dimensions are incompatible fill between curves


I have this plot.

fig,ax = plt.subplots(figsize=(7.5,7.5))

ax.plot(time, y)
ax.plot(time, y1, color='red')
ax.plot(time, y2, color='black')

enter image description here

I want to fill the area between the black and red curves. So I am doing:

y1=np.array(y1)
y2=np.array(y2)
ax.fill_between(time, y1, y2,where=y1>=y2,color='grey', alpha='0.5')

But it returns the following:

ValueError: Argument dimensions are incompatible

Solution

  • In your case, you do not need to put a where condition for what you want to do. fill_between function only requires to put the maximum array and minimum array for your proposal of equal length of OX array (time in your case).

    The following is an example:

    import numpy as np
    import matplotlib.pyplot as plt
    
    fig,ax = plt.subplots(figsize=(7.5,7.5))
    
    time = np.linspace(0,1,100)
    y = np.sin(time*10)
    y1 = y - 0.5
    y2 = y + 0.5
    
    ax.plot(time, y)
    ax.plot(time, y1, color='red')
    ax.plot(time, y2, color='black')
    
    ax.fill_between(time, y1, y2, color='grey', alpha='0.5')
    
    plt.tight_layout()
    plt.show()
    

    That gives the following output: enter image description here

    To see how where works, change the line to this one in my example:

    ax.fill_between(time, y1, y2, where=(time<0.5), color='grey', alpha='0.5')
    

    Or this as another conditional example:

    ax.fill_between(time, y1, y2, where=(y1<0.0), color='grey', alpha='0.5')
    

    As you can see, what it makes is to create a boolean array and draws only on that points of OX axis where the condition is true. You can make your boolean array by hand also (length of OX axis, of course).