shade region of interest in matplotlib chart

Question:

Given a plot like

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(s)
ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='sine')
ax.grid()
plt.show()

How can I shade the vertical slices (from bottom to top) of the chart where the y-value of the plot is between (e.g.) 1.25 and 0.75 automatically?

the sine is just a sample here, the actual values of the plot are less regular.

I have seen FIll between two vertical lines in matplotlib, which looks similar to this question, but the answer there shades a region between fixed x values. I want the shaded region to be determined by the y values.

Asked By: retorquere

||

Answers:

You can use ax.axvspan, which apparently does exactely what you want. For better results, usa an alpha value below 0.5, and optionally set color and edge-color/width.

fig, ax = plt.subplots()
ax.plot(s)
ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='sine')
ax.axvspan(0.75, 1.25, alpha=0.2)
ax.grid()
plt.show()

If you want the shading to be in a different orientation (horizontal instead of vertical), there is also the ax.axhspan method.

Answered By: heltonbiker

You might be looking for ax.fill_between, which is pretty flexible (see the linked documentation).

For your specific case, if I understand correctly, this should be enough:

fig, ax = plt.subplots()
ax.plot(s)
ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='sine')
ax.fill_between(range(len(s)), min(s), max(s), where=(s < 1.25) & (s > 0.75), alpha=0.5)
ax.grid()

enter image description here

Answered By: sacuL
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.