Issue
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
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?
Solution
Using pyplot.stairs
as an alternative gives the desired results. You may need to do a small transformation to take you from x-centers to x-edges.
from matplotlib import pyplot as plt
years = [2008, 2009, 2010, 2011, 2012, 2013]
data = [125, 78, 113, 56, 98, 140]
# convert from mid points to edges
width = 1 # one year steps
year_edges = []
for year in years:
year_edges.append(year + width/2)
year_edges.insert(0,year_edges[0] - width)
fig, ax = plt.subplots(figsize=(6,4))
ax.stairs(data, year_edges,lw=1)
plt.show()
This produces:
I appreciate this is a very late answer but found this thread when having a similar issue when trying to draw a step plot with the counts/bin-centers of a previously produced histogram.
Searching online brought me here, and I subsequently found a solution that I hope can help others.
Answered By - Paidoo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.