将哈希模式应用于条形图

2024-06-27 20:46:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个列表,在那里我可以添加英语国家,并确保在我的条形图上反映出来

top9 = master_frame[master_frame['country_code'].isin(["USA","CHN","GBR","IND","CAN","ISR","FRA","DEU","SWE"])]

plt.figure(figsize=(10,5))
ax2=sns.barplot(x='country_code', y='raised_amount_usd', data=top9, estimator=np.sum,)
ax2.set_yscale('log')
ax2.set(xlabel='Funding by country', ylabel='Total amount of investments')
ax2.set_title('Investment distribution Country wise',fontsize =18, weight='bold')
plt.show()

输出:

barplot image

这里的挑战是,我需要强调以英语为官方语言的国家,因此我的想法是在这些国家的栏中添加一个哈希模式,并在上面显示一个色调框

你知道我怎样才能做到这一点吗

提前谢谢你


Tags: master列表codeplt国家amountframecountry
1条回答
网友
1楼 · 发布于 2024-06-27 20:46:50

我不太确定你提到的散列模式

这是我的理解,你要做到两件事

首先,给具有不同属性的条上色

其次,在绘图上创建一个图例框

下面的方法是实现您的目标的方法


一,。给条子上色

通过在函数sns.barplot中设置参数palette,可以轻松完成此步骤。您应以十六进制格式输入一系列颜色(也存在lots of other ways

color_eng = "#94698b"
color_non_eng = "#4369ef"

# the sequence length is the number of bars.
palette = [color_eng, color_eng, color_non_eng, color_eng, color_non_eng]

ax2 = sns.barplot(x='country_code', y='raised_amount_usd', 
                  data=top9, estimator=np.sum, palette=palette)

二,。创建一个图例

要创建自定义的图例框,我们可以使用手动创建的patches设置轴的句柄(我借用了this SO answer的代码思想)

import matplotlib.patches as mpatches

p_eng = mpatches.Patch(color=color_eng, label='English speaking country')
p_non_eng = mpatches.Patch(color=color_non_eng, label='non-English speaking country')

ax2.legend(handles=[p_eng, p_non_eng])

最终代码如下所示:

import matplotlib.patches as mpatches

top9 = master_frame[master_frame['country_code'].isin(["USA","CHN","GBR","IND","CAN","ISR","FRA","DEU","SWE"])]

plt.figure(figsize=(10,5))

color_eng = "#94698b"
color_non_eng = "#4369ef"

# the sequence length is the number of bars.
# Shall be composed by you
palette = [color_eng, color_eng, color_non_eng, color_eng, .......]

ax2 = sns.barplot(x='country_code', y='raised_amount_usd', 
                  data=top9, estimator=np.sum, palette=palette)

p_eng = mpatches.Patch(color=color_eng, label='English speaking country')
p_non_eng = mpatches.Patch(color=color_non_eng, label='non-English speaking country')

ax2.legend(handles=[p_eng, p_non_eng])

ax2.set_yscale('log')
ax2.set(xlabel='Funding by country', ylabel='Total amount of investments')
ax2.set_title('Investment distribution Country wise',fontsize =18, weight='bold')
plt.show()

相关问题 更多 >