Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create overlay bar plot in pandas

While updating some of my earlier code to use pandas.DataFrame, I'm got stuck with following problem...

This is the reference plot that my original code would create:

import pandas as pd
import matplotlib.pyplot as plt

a = range(1, 25)
b = a
c = [x+2 for x in b]
d = [x*2 for x in c]

plt.bar(a, d)
plt.bar(a, c)
plt.bar(a, b)
plt.show()

reference plot

Problem definition:

I would like to create this very same plot using pandas.DataFrame built in functionality. To be precise, only the bars placement is relevant, I'm not interested in the formatting/labeling of axis ticks.

df = pd.DataFrame({'a': a, 'b': b, 'c': c, 'd': d}, columns=['a', 'b', 'c', 'd'])
df.set_index('a', inplace=True)

df.plot.bar()
plt.show()

first pandas plot

Neither, default pandas bar-plot (shown above) nor adding stacked=True option (see below), produced the desired result.

df.plot.bar(stacked=True)
plt.show()

second pandas plot

Unfortunately,overlay=True option does not exist.

Is there another (preferably elegant) way to achieve the desired result?

If nothing else is available, I will just modify the pandas.DataFrame values (i.e. subtract the columns from each other) and then use stacked=True option. Before, I implement that, I'm looking forward to see your suggestions...

like image 531
Boris L. Avatar asked May 03 '18 14:05

Boris L.


1 Answers

You can set the ax parameter with the value returned by subplots, like this:

_, ax = plt.subplots()
df.d.plot(kind='bar', ax=ax, color='red')
df.c.plot(kind='bar', ax=ax, color='green')
df.b.plot(kind='bar', ax=ax, color='blue')

enter image description here

like image 115
Ami Tavory Avatar answered Oct 09 '22 21:10

Ami Tavory