Matplotlib plot only horizontal lines in step plot

后端 未结 1 427
死守一世寂寞
死守一世寂寞 2021-01-06 18:03

I am using matplotlib to plot some step functions from a dataframe

df[\'s1\'].plot(c=\'b\', drawstyle=\"steps-post\")
df[\'s2\'].plot(c=\'b\', drawstyle=\"st         


        
相关标签:
1条回答
  • 2021-01-06 18:25

    There is no built-in option to produce a step function without vertical lines as far as I can tell. But you may easily build one yourself. The following uses the fact that np.nan is not plotted and cuts the line. So adding np.nan in between the steps suppresses the vertical line.

    import matplotlib.pyplot as plt
    import numpy as np
    
    def mystep(x,y, ax=None, where='post', **kwargs):
        assert where in ['post', 'pre']
        x = np.array(x)
        y = np.array(y)
        if where=='post': y_slice = y[:-1]
        if where=='pre': y_slice = y[1:]
        X = np.c_[x[:-1],x[1:],x[1:]]
        Y = np.c_[y_slice, y_slice, np.zeros_like(x[:-1])*np.nan]
        if not ax: ax=plt.gca()
        return ax.plot(X.flatten(), Y.flatten(), **kwargs)
        
    x = [1,3,4,5,8,10,11]
    y = [5,4,2,7,6,4,4]
    
    mystep(x,y, color="crimson")
    
    plt.show()
    

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