Search code examples
pythonpython-3.xmatplotlibarea

transparatent "overlay" matplotlib stackplot


I have a simple stackplot:

import matplotlib.pyplot as plt

label, color = ["R", "M"], ["green", "blue"]
X = [x for x in range(101)]
Y1 =  [31.4*x for x in range(101)]
Y2 = [26.51*x-250 if (26.51*x-250)>=0 else 0 for x in range(101)]
Y3 =  [31.4*x if 31.4*x < 2400 else 2400 for x in range(101)]

plt.stackplot(X, Y1, Y2, labels=label, colors = color)
plt.fill_between(X,Y3,[2400 for x in range(101)], color = 'r')
plt.legend(loc=2)
plt.xlim(0,100)
plt.ylim(0,5600)
plt.show()

There might be a better way to display what I want to display, but I would just like to know how, if possible, to make the red area transparent with matplotlib.

enter image description here


Solution

  • If I understood correctly, do you need something like the following?

    In that case, you can specify the transparency of fill_between

    import matplotlib.pyplot as plt
    
    label, color = ["R", "M"], ["green", "blue"]
    X = [x for x in range(101)]
    Y1 =  [31.4*x for x in range(101)]
    Y2 = [26.51*x-250 if (26.51*x-250)>=0 else 0 for x in range(101)]
    Y3 =  [31.4*x if 31.4*x < 2400 else 2400 for x in range(101)]
    
    plt.stackplot(X, Y1, Y2, labels=label, colors = color)
    plt.fill_between(X,Y3,[2400 for x in range(101)], color = 'r', alpha=0.3)
    plt.legend(loc=2)
    plt.xlim(0,100)
    plt.ylim(0,5600)
    

    enter image description here