Reputation: 474
I am new to matplotlib and cannot figure out how to stack multiple series into one bar chart.
Here is some data:
import pandas as pd
import matplotlib.pyplot as plt
###Data
x_lab = pd.Series(['a','b','c'])
Series1 = pd.Series([25,35,30])
Series2 = pd.Series([40,35,50])
Series3 = pd.Series([35,30,20])
##Creating the 3 bars to plot##
pl_1 = plt.bar(x= x_lab,height = Series1)
pl_2 = plt.bar(x= x_lab,height = Series2)
pl_3 = plt.bar(x= x_lab,height = Series3)
When I run this code the data is superimposed onto each other. I am hoping that the data would be able to be stacked instead.
I have tried this:
##First attempt
attempt_1 = plt.bar(x = x_lab, height = [pl_1,pl_2,pl_3], stacked = True)
And this:
##Second Attempt
pl_1 = plt.bar(x= x_lab,height = Series1, stacked = True)
pl_2 = plt.bar(x= x_lab,height = Series2, stacked = True)
pl_3 = plt.bar(x= x_lab,height = Series3, stacked = True)
But neither worked. The desired output wold look something like this (colors do not need to match):
Any help or guidance would be greatly appreciated.
Upvotes: 1
Views: 188
Reputation: 59529
concat
+ a bar plot with stacked=True
import pandas as pd
(pd.concat([Series1, Series2, Series3], axis=1)
.assign(idx=x_lab).set_index('idx') # just for the labeling
.plot.bar(stacked=True))
Upvotes: 3