我正在嘗試創建一個堆疊條形圖,并使用我存盤在變數中的顏色名稱為條形著色party_color。
這是我的嘗試:
import pandas as pd
import matplotlib.pyplot as plt
marginal_electorates_2016 = {'margin': {0: 'Fairly safe', 1: 'Fairly safe', 2: 'Fairly safe', 3: 'Marginal', 4: 'Marginal', 5: 'Marginal', 6: 'Marginal', 7: 'Safe', 8: 'Safe', 9: 'Safe', 10: 'Safe'},
'PartyNm': {0: 'Australian Labor Party', 1: "Katter's Australian Party", 2: 'Liberal/National Coalition', 3: 'Australian Labor Party', 4: 'Independent', 5: 'Liberal/National Coalition', 6: 'Nick Xenophon Team', 7: 'Australian Labor Party', 8: 'Independent', 9: 'Liberal/National Coalition', 10: 'The Greens'},
'count': {0: 32, 1: 1, 2: 29, 3: 24, 4: 1, 5: 28, 6: 1, 7: 13, 8: 1, 9: 19, 10: 1},
'party_color': {0: 'red', 1: 'yellow', 2: 'blue', 3: 'red', 4: 'pink', 5: 'blue', 6: 'orange', 7: 'red', 8: 'pink', 9: 'blue', 10: 'green'}}
marginal_electorates_2016 = pd.DataFrame(marginal_electorates_2016)
margin PartyNm count party_color
0 Fairly safe Australian Labor Party 32 red
1 Fairly safe Katters Australian Party 1 yellow
2 Fairly safe Liberal/National Coalition 29 blue
3 Marginal Australian Labor Party 24 red
4 Marginal Independent 1 pink
5 Marginal Liberal/National Coalition 28 blue
6 Marginal Nick Xenophon Team 1 orange
7 Safe Australian Labor Party 13 red
8 Safe Independent 1 pink
9 Safe Liberal/National Coalition 19 blue
10 Safe The Greens 1 green
plt.figure(figsize=(16, 6))
marginal_electorates_2016.plot(
kind = 'bar',
x = ['margin', 'PartyNm'],
y = 'count',
stacked = False,
subplots = True,
figsize = [10,15],
sharey = True,
c = 'party_colour'
)
plt.tight_layout
uj5u.com熱心網友回復:
- 繪制條形組的最簡單方法是將資料框從長格式改成寬格式
- 和
stacked=True

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/374562.html標籤:Python 熊猫 matplotlib 条形图
- 和
