How do I use axvfill with a boolean series

后端 未结 1 1514
粉色の甜心
粉色の甜心 2020-12-19 21:39

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.ind         


        
相关标签:
1条回答
  • 2020-12-19 22:21

    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()
    

    0 讨论(0)
提交回复
热议问题