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.
fill_between() is used to fill area between two horizontal curves. Two points (x, y1) and (x, y2) define the curves. this creates one or more polygons describing the filled areas.
%matplotlib inline sets the backend of matplotlib to the 'inline' backend: With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.
It sounds like you want axvspan
, rather than one of the fill between functions. The differences is that axvspan
(and axhspan
) will fill up the entire y (or x) extent of the plot regardless of how you zoom.
For example, let's use axvspan
to highlight the x-region between 8 and 14:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(range(20))
ax.axvspan(8, 14, alpha=0.5, color='red')
plt.show()
You could use fill_betweenx
to do this, but the extents (both x and y) of the rectangle would be in data coordinates. With axvspan
, the y-extents of the rectangle default to 0 and 1 and are in axes coordinates (in other words, percentages of the height of the plot).
To illustrate this, let's make the rectangle extend from 10% to 90% of the height (instead of taking up the full extent). Try zooming or panning, and notice that the y-extents say fixed in display space, while the x-extents move with the zoom/pan:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(range(20))
ax.axvspan(8, 14, ymin=0.1, ymax=0.9, alpha=0.5, color='red')
plt.show()
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