Issue
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.
Solution
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()
Answered By - sacuL
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.