Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shading an area between two points in a matplotlib plot

How do you add a shaded area between two points in a matplotlib plot?

In the example matplotlib plot below, I manually added the shaded, yellow area using Skitch. I'd like to know how to do this sans-Skitch.

alt text

like image 526
Matthew Rankin Avatar asked Sep 10 '10 02:09

Matthew Rankin


People also ask

How do I color an area between two lines in python?

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.

How do I fill an area in Matplotlib?

To fill the area under the curve, put x and y with ste="pre", using fill_between() method. Plot (x, y1) and (x, y2) lines using plot() method with drawstyle="steps" method. To display the figure, use show() method.


1 Answers

You can just use the function axvspan. The advantage to this is that the vertical region (or horizontal, in the case of axhspan) will remain shaded regardless of how you pan/zoom the plot. There's a complete example here.

See a simple example below:

import numpy as np import matplotlib.pyplot as plt  x = np.linspace(0, 20, 500) y = np.cos(3*x) - 2*np.cos(5*x) + 0.5*np.cos(6*x)  a = 5 b = 15  plt.axvspan(a, b, color='y', alpha=0.5, lw=0) plt.plot(x, y) plt.savefig('shade.png', dpi=300) plt.show() 

That gives as a result enter image description here

like image 199
nicoguaro Avatar answered Sep 21 '22 04:09

nicoguaro