123py
123py

Reputation: 61

pandas area plot interpolation / step style

Is there a way to disable the interpolation in the pandas area plot? I would like to get a "step-style" area plot. E.g. in the normal line plot it is possible to specify:

import pandas as pd
df = pd.DataFrame({'x':range(10)})
df.plot(drawstyle = 'steps') # this works
#df.plot(kind = 'area', drawstyle = 'steps') # this does not work

I am using python 2.7 and pandas 0.14.1.

Many thanks in advance.

Upvotes: 6

Views: 4593

Answers (3)

horseshoe
horseshoe

Reputation: 1477

with area this isnot possbile but you can use a stacked bar plot do get what you want

import pandas as pd
df = pd.DataFrame({'x':range(10)})
df.plot(kind="bar",stacked=True,width = 1)

enter image description here

Upvotes: 1

Martin
Martin

Reputation: 1475

Recently an update of .fill_between() was shipped with matplotlib version 1.5.0 that allows to fill the area between two step functions. This even works with Pandas time series.

Since the argument step='pre' exists, it can be used like this:

# For error bands around a series df
ax.fill_between(df.index, df - offset, df + offset, step='pre', **kwargs)

# For filling the whole area below a function
ax.fill_between(df.index, df, 0, step='pre', **kwargs)

Additional key word arguments that make sense to me are for example alpha=0.3 and lw=0.

Upvotes: 5

cphlewis
cphlewis

Reputation: 16269

As far as I can tell, df.plot(drawstyle="steps") doesn't even store the calculated step vertices;

out = df.plot(kind = 'line', drawstyle = 'steps') # stepped, not filled
stepline = out.get_lines()[0]
print(stepline.get_data())

(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))

so I think you'll have to roll your own. Which is just inserting (x[i+1],y[i]) directly after every (x[i],y[i]) in the list of points:

df = pd.DataFrame({'x':range(10)})
x = df.x.values
xx = np.array([x,x])
xx.flatten('F')
doubled = xx.flatten('F') # NOTE! if x, y weren't the same, need a yy
plt.fill_between(doubled[:-1], doubled[1:], label='area')
ax = plt.gca()
df.plot(drawstyle = 'steps', color='red', ax=ax) 

enter image description here

Upvotes: 2

Related Questions