我有一個 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)
uj5u.com熱心網友回復:
采用:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/476705.html
標籤:Python 熊猫 matplotlib
