I have a Pandas dataframe with categorical data stored in a list. I would like to plot a stacked bar plot with col3 on the x-axis and col1 and col2 stacked on top of each other for the y-axis.
Reproducible dataframe structure:
import pandas as pd
import matplotlib.pyplot as plt
d = {'col1': [1, 17, 40],
'col2': [10, 70, 2],
'col3': [['yellow', 'green', 'blue'],
['yellow', 'orange', 'blue'],
['blue', 'green', 'pink']]}
df = pd.DataFrame(data=d)
CodePudding user response:
Use:
df.explode('col3').set_index('col3').plot.bar(stacked=True)
Or:
df1 = (df.explode('col3')
.melt('col3')
.pivot_table(index='col3', columns='variable', values='value', aggfunc='sum'))
df1.plot.bar(stacked=True)