9

In pandas' documentation you can find a discussion on area plots, and in particular stacking them. Is there an easy and straightforward way to get a 100% area stack plot like this one

enter image description here

from this post?

Community
  • 1
  • 1
Dror
  • 12,174
  • 21
  • 90
  • 160

1 Answers1

16

The method is basically the same as in the other SO answer; divide each row by the sum of the row:

df = df.divide(df.sum(axis=1), axis=0)

Then you can call df.plot(kind='area', stacked=True, ...) as usual.


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
np.random.seed(2015)

y = np.random.randint(5, 50, (10,3))
x = np.arange(10)
df = pd.DataFrame(y, index=x)

df = df.divide(df.sum(axis=1), axis=0)
ax = df.plot(kind='area', stacked=True, title='100 % stacked area chart')

ax.set_ylabel('Percent (%)')
ax.margins(0, 0) # Set margins to avoid "whitespace"

plt.show()

yields

enter image description here

Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • 1
    Another possibility is `pandas.DataFrame.plot.area()` – Dror Mar 29 '17 at 08:18
  • `ax.margins(0, 0)` is fragile and frequently won't work as expected. `ax.autoscale(enable=True, axis='both', tight=True)` is better in modern matplotlib. – Mark_Anderson Oct 22 '21 at 21:37