Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
791 views
in Technique[技术] by (71.8m points)

python - How do I use axvfill with a boolean series

I have a boolean time series that I want to use to determine the parts of the plot that should be shaded.

Currently I have:

ax1.fill_between(data.index, r_min, r_max, where=data['USREC']==True, alpha=0.2)

where, r_min and r_max are just the min and max of the y-axis.

But the fill_between doesn't fill all the way to the top and bottom of the plot because, so I wanted to use axvspan() instead.

Is there any easy way to do this given axvspan only takes coordinates? So the only way I can think of is to group all the dates that are next to each other and are True, then take the first and last of those dates and pass them into axvspan.

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can still use fill_between, if you like. However instead of specifying the y-coordinates in data coordinates (for which it is not a priori clear, how large they need to be) you can specify them in axes coorinates. This can be achieved using a transform, where the x part is in data coordinates and the y part is in axes coordinates. The xaxis transform is such a transform. (This is not very surprising since the xaxis is always independent of the ycoorinates.) So

ax.fill_between(data.index, 0,1, where=data['USREC'], transform=ax.get_xaxis_transform())

would do the job.

Here is a complete example:

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(0)

x = np.linspace(0,100,350)
y = np.cumsum(np.random.normal(size=len(x))) 
bo = np.zeros(len(y))
bo[y>5] = 1

fig, ax = plt.subplots()
ax.fill_between(x, 0, 1, where=bo, alpha=0.4, transform=ax.get_xaxis_transform())

plt.plot(x,y)
plt.show()

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...