如何将两列熊猫数据框绘制为水平条形图?

时间:2018-12-18 18:23:28

标签: python pandas matplotlib plot seaborn

我正在尝试在数据框中的2列之间进行比较,并希望使用Seaborn将其绘制为水平条形图。在下面的图中,仅绘制了一个列(“ budget2019”)。

actual plot with just one year 'budget2019' plotted

1)我如何绘制第二列(“ budget2018”)旁边的内容,以便每个“部委”都能更好地看到两列值之间的变化,并直观地比较两个条形?

2)如何将x值放在每个小节的末尾,这样就可以看到(读取)每个小节上的x值,而不必睁大眼睛,而是尝试近似价值?因为现在在实际绘图上,不能真正从条形图上直接读取x值。 (在查看绘图时很难获得确切的值)

3)在我将其绘制在“ budget2019”条旁边的“ budget2018”条之后,是否有办法将演变的百分比表示在该图上?为了使它在视觉上更具可读性,两列之间的百分比差异是多少?

这是我的数据框:

a part of my small dataframe

这是我现在要绘制的代码:

plt.figure(figsize=(15,8))

sns.set(style="darkgrid")

#ax = sns.barplot(x="budget2018", y="ministere", data=budget, label="Total")
sns.set_color_codes("pastel")
sns.barplot(x="budget2019", y="ministere", data=budget, label="Budget 2019")

sns.despine(left=True, bottom=True)

plt.tight_layout()
plt.show()

PS:如果不能用Seaborn做到这一点,那么仅使用Matplotlib解决方案也是可以的。就像我的情节一样,需要的是水平条,否则yticks无法读取。

编辑(使用ImportanceOfBeingErnest注释中的代码后):

这是@ImportanceOfBeingErnest评论后我实际看到的情节。它非常接近我的需求。

plot after @ImportanceOfBeingErnest's comment (setting index)

1 个答案:

答案 0 :(得分:0)

要使用seaborn,必须使用使用melt创建的中间数据帧来生成“长格式”数据帧。

df2 = pd.melt(budget, id_vars=['ministere'], value_vars=['budget2018','budget2019'], var_name='year')

然后使用hue=参数完成两列的绘制:

fig,ax = plt.subplots()
sns.set_color_codes("pastel")
sns.barplot(x="value", y="ministere", hue="year", data=df2, palette='pastel')

根据要求调整标签相当容易(并且您会在SO上找到很多其他实例):

for i,m in budget.iterrows():
    ax.annotate(s='{:.2f}%'.format(m.loc['evolution_percent']),
                xy=(m.loc[['budget2018','budget2019']].max(),i),
                xytext=(10,0),
                textcoords='offset pixels',
                ha='left',
                va='center'
               )

labels = ['{:s}\n(2019: {:.2f}€)'.format(d.ministere,d.budget2019) for _,d in budget.iterrows()]
ax.set_yticklabels(labels)

enter image description here

相关问题