使用 Pandas 绘制包含分类列表的堆叠列

Plotting a stacked column containing a categorical list using Pandas

我有一个 Pandas 数据框,其中分类数据存储在列表中。我想绘制一个堆叠条形图,其中 col3 在 x 轴上,col1 和 col2 在 y 轴上彼此堆叠。

可重现的数据帧结构:

    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)

使用:

df.explode('col3').set_index('col3').plot.bar(stacked=True)

或者:

df1 = (df.explode('col3')
        .melt('col3')
        .pivot_table(index='col3', columns='variable', values='value', aggfunc='sum'))

df1.plot.bar(stacked=True)