How to efficiently create a line plot with connected horizontal lines per data point?

Viewed 33

I want to create a plot like this: Connected horizontal line plot

I know how to create horizontal lines in Matplotlib, and I see a way of creating many short horizontal lines and to connect them with short vertical lines, but I have the intuition that a better way is possible.

I have tried this code myself:

import matplotlib.pyplot as plt
y = [1, 1, 3, 3, 6, 6]
x = [1, 2, 2, 3, 3, 4]

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

It produces this plot.

It has the basics of what I want, but since I have data per month, creating a plot like this requires some awkward data manipulation.

Lastly, I also thought of creating a bar plot which only show the top line of the bar, which would nicely create the horizontal lines, but they would not be connected.

Thanks in advance for your help!

1 Answers

You initial intuition was correct, you can generate a list of the successive points with simple numpy array reshaping:

import numpy as np

x = np.array([0,1,2,3,4,5,6,7,8])
y = np.array([1,2,3,2,5,4,2,0,2])

x2 = np.c_[x-0.5,x+0.5].ravel()
y2 = np.c_[y,y].ravel()

plt.plot(x2, y2)

That said, this is all automated by matplotlib.pyplot.step, it has a where parameter to define the alignment (for example on the mid point):

plt.step(x, y, where='mid')

output:

step plot

Related