Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

100% area plot of a pandas DataFrame

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?

like image 337
Dror Avatar asked Apr 29 '15 10:04

Dror


People also ask

How do you plot an area in Python?

To get an area plot for a pandas DataFrame, make a Python call: dataFrameinstance. plot. area().

How do I change the size of a pandas DataFrame plot?

The size of a plot can be modified by passing required dimensions as a tuple to the figsize parameter of the plot() method. it is used to determine the size of a figure object.

How do I visualize pandas DataFrame?

In order to visualize data from a Pandas DataFrame , you must extract each Series and often concatenate them together into the right format. It would be nicer to have a plotting library that can intelligently use the DataFrame labels in a plot.


1 Answers

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

like image 75
unutbu Avatar answered Oct 31 '22 03:10

unutbu