I would like to fill between 3 lines in matplotlib.pyplot but unfortunately the fill_between
gives me opportunity to fill between only two lines. Any ideas how to deal with this?
Edit:
Ok, I did not explain what I really mean since I cannot add the picture with my current reputation so maybe in that way:
I try to fill the polygon bounded by these lines and I have no idea how because fill_between gives me opportunity to fill only area between two of them. Below the fill equation:
y <= 4- 2x y <= 3 - 1/2x y <= 1 - x y >= 0 x >= 0
the x and y bigger than 0 is obvious. I start the plot from (0,0) but I still have 3 lines...
y <= 4- 2x y <= 3 - 1/2x y <= 1 - x
We can fill an area between multiple lines in Matplotlib using the matplotlib. pyplot. fill_between() method. The fill_between() function fills the space between two lines at a time, but we can select one pair of lines to fill the area between multiple lines.
MatPlotLib with Python To shade the regions between curves, we can use the fill_between() method.
Matplotlib fill between three linesFirstly we fill the area, between y1 and y2 by using the fill_between() method and we set the color red by using the parameter color. Then we fill the area, between y2 and y3 by using the fill_between() method and we set its color to yellow by using a color parameter.
You can easily fill in the area between values in a Matplotlib plot by using following functions: fill_between(): Fill the area between two horizontal curves. fill_betweenx(): Fill the area between two vertical curves.
If you start the plot in point (0, 0), and therefore do not need to consider the area of the polygon not in the first quadrant, then this should do the trick in this particular situation:
import matplotlib.pyplot as plt import numpy as np x = np.arange(0,10,0.1) # The lines to plot y1 = 4 - 2*x y2 = 3 - 0.5*x y3 = 1 -x # The upper edge of polygon (min of lines y1 & y2) y4 = np.minimum(y1, y2) # Set y-limit, making neg y-values not show in plot plt.ylim(0, 5) # Plotting of lines plt.plot(x, y1, x, y2, x, y3) # Filling between line y3 and line y4 plt.fill_between(x, y3, y4, color='grey', alpha='0.5') plt.show()
To use fill_between
, specify the X values first, than the two Y sets that you want to "fill between". An example is show below:
import pylab as plt import numpy as np X = np.linspace(0,3,200) Y1 = X**2 + 3 Y2 = np.exp(X) + 2 Y3 = np.cos(X) plt.plot(X,Y1,lw=4) plt.plot(X,Y2,lw=4) plt.plot(X,Y3,lw=4) plt.fill_between(X, Y1,Y2,color='k',alpha=.5) plt.fill_between(X, Y1,Y3,color='y',alpha=.5) plt.show()
If, instead, you only wanted to fill between Y2 and Y3:
plt.fill_between(X, Y2,Y3,color='m',alpha=.5)
this would give you
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With