如何根据列中的颜色为条形图着色
Posted
技术标签:
【中文标题】如何根据列中的颜色为条形图着色【英文标题】:How to pivot a dataframe to plot bars 【发布时间】:2022-01-10 10:38:32 【问题描述】:我正在尝试创建一个堆积条形图,并使用我存储在变量 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
【问题讨论】:
【参考方案1】: 绘制条形组的最简单方法是使用pandas.DataFrame.pivot
将数据框从长格式改造成宽格式
创建一个颜色dict
,派对为key
,颜色为value
,绘图时可以传递给color
参数。
有多种方法可以将两列转换为dict
,其中一列为keys
,另一列为values
。使用哪种方式并不重要。 How to create a dictionary of two pandas DataFrame columns
直接使用pandas.DataFrame.plot
和kind='bar'
绘制数据框。如果需要,可以将stacked=True
用于堆积条形图,但我不建议这样做,因为它会使数据更难比较。
import pandas as pd
import matplotlib.pyplot as plt
# create the dataframe
df = pd.DataFrame(marginal_electorates_2016)
# transform the shape
dfp = df.pivot(index='margin', columns='PartyNm', values='count')
# display(dfp)
PartyNm Australian Labor Party Independent Katters Australian Party Liberal/National Coalition Nick Xenophon Team The Greens
margin
Fairly safe 32.0 NaN 1.0 29.0 NaN NaN
Marginal 24.0 1.0 NaN 28.0 1.0 NaN
Safe 13.0 1.0 NaN 19.0 NaN 1.0
# create a colors dict
colors = dict(df[['PartyNm', 'party_color']].drop_duplicates().to_numpy())
# plot
ax = dfp.plot(kind='bar', rot=0, color=colors, figsize=(16, 6))
ax.legend(bbox_to_anchor=(1, 1.02), loc='upper left')
与stacked=True
【讨论】:
以上是关于如何根据列中的颜色为条形图着色的主要内容,如果未能解决你的问题,请参考以下文章