Chanber Liou
Chanber Liou

Reputation: 95

How to make Python chart that only contain Vertical and horizontal Lines?

How to draw something like this? There's kind of like a horizontal line until next data point show up, then a vertical line to adjust the location y. The usual plot function in matplotlib just plot a straight line between two data point, which doesn't satisfy what I need.

The example screenshot

Upvotes: 8

Views: 1572

Answers (2)

Thomas Kühn
Thomas Kühn

Reputation: 9810

Just as @cricket_007 said in the comments -- make each y value repeat at the next x value. Below a way how to achieve this with numpy.

EDIT:

Thanks to the comment by @ImportanceOfBeingErnest I replaced the original code that extended the data with a much simpler solution.

from matplotlib import pyplot as plt
import numpy as np

#producing some sample data
x = np.linspace(0,1,20)
y = np.random.rand(x.shape[0])

#extending data to repeat each y value at the next x value  
##x1 = np.zeros(2*x.shape[0]-1)
##x1[::2] = x
##x1[1::2] = x[1:]
x1 = np.repeat(x,2)[1:]

##y1 = np.zeros(2*y.shape[0]-1)
##y1[::2] = y
##y1[1::2] = y[:-1]
y1 = np.repeat(y,2)[:-1]

plt.plot(x1, y1)    
plt.show()

The result looks like this:

result of the code above

Upvotes: 0

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339280

You may use one of the drawstyles "steps-pre", "steps-mid", "steps-post" to get a a step-like appearance of your curve.

plt.plot(x,y, drawstyle="steps-pre")

Full example:

import matplotlib.pyplot as plt
import numpy as np; np.random.seed()

x = np.arange(12)
y = np.random.rand(12)

styles = ["default","steps-pre","steps-mid", "steps-post"]

fig, axes = plt.subplots(nrows=len(styles), figsize=(4,7))

for ax, style in zip(axes, styles):
    ax.plot(x,y, drawstyle=style)
    ax.set_title("drawstyle={}".format(style))

fig.tight_layout()
plt.show()

enter image description here

Upvotes: 9

Related Questions