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()
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()
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()
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...
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With