简体   繁体   中英

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.

替代文字

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 在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM