pyplot step function does not draw a level for first/last point

Viewed 1974

I am attempting to create a step plot that has a horizontal step or level for each point in the input data. Regardless of whether you specify "pre" or "post" for the where argument, pyplot.step will not do this. If you specify "pre", it will draw a vertical line from the first point, but no step for that value. If you specify "post", the opposite occurs. See code below for a demo of this.

from matplotlib import pyplot as plt

#Series to plot
years = [2008, 2009, 2010, 2011, 2012, 2013]
data = [125, 78, 113, 56, 98, 140]

#Plot series
fig, ax = plt.subplots(figsize=(6,4))
ax.step(years, data, where='post')
plt.show()

Output of above

enter image description here

For context, the application is a time series plot that shows a horizontal level for the time period corresponding to each y value. I have a data set where each point represents a summary statistic for a year, so each y value applies to an entire year, not a single point in time. Therefore, the step plot seems an intuitive way to show this. I realize a bar graph or histogram might provide more control regarding my issue, but, since I have continuous data series, a line plot is preferable.

Is there a way to alter this behavior so that a horizontal line is drawn for all of the points, including BOTH the first and last points?

1 Answers

The issue here is that pyplot does not know where your "next" x value is, ie. doesn't know up to which point to extend the horizontal line. So you need to manually add another x value to the end (post) or beginning (pre), and copy the last/first y value.

Related