Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib plot only horizontal lines in step plot

Tags:

matplotlib

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

enter image description here

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?

like image 681
chrise Avatar asked Jul 07 '17 01:07

chrise


1 Answers

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

enter image description here

like image 94
ImportanceOfBeingErnest Avatar answered Jan 02 '23 12:01

ImportanceOfBeingErnest