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="steps-post")
...
The result looks like
I would like to have this only plot the horizontal lines, not the vertical lines connecting the jump points. I could not find a straightforward parameter for plot that would seem to do that. Is there a way to do this?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With