首页 > 解决方案 > 标记 2x2 子图中每个条形上方的所有条形图值

问题描述

我有一个由 4 个 Seaborn 条形图组成的 2x2 子图。我想将每个图表中每个条的值添加到每个条的顶部。

我可以添加文本并手动定位它,我已经尝试过了,但我知道这是低效的,必须有更好的方法。

我似乎无法弄清楚如何获得其他人为单个条形图在子图上工作的解决方案。

这是我的代码:

数据:

vis = pd.DataFrame({'Win %': [52.631579, 59.736842, 50.657895, 42.609649],
                    'Made Playoffs': [7,12,8,4],
                    'Won NFC Championship': [0,2,3,0],
                    'Won Super Bowl': [0,1,2,0]},
                    index=['Cowboys','Eagles','Giants','Redskins'])
vis = test.reset_index()
vis = test.rename(columns={'index':'Team'})

绘图:

fig, ((ax1,ax2), (ax3,ax4)) = plt.subplots(2,2, sharex=True, sharey=False, figsize=(10,10))

fig.suptitle('NFC East Division Rivals, 2000-2018')
fig.subplots_adjust(wspace=0.5, hspace=0.3)

for ax in plt.gcf().get_axes():
    for label in ax.get_xticklabels() + ax.get_yticklabels():
        label.set_visible(True)

sns.set_style("darkgrid", {'font.sans-serif':'sans-serif', 'text.color':'#1e1e1e'})

# Win %
sns.barplot(x='Team',y='Win %',data=vis, palette=colors, 
            edgecolor=edges, linewidth=2, ax=ax1)

ax1.title.set_text('Average Win %')
ax1.set_ylabel('')
ax1.set_xlabel('')

for i, v in enumerate(df['Win %']):
    ax1.text(v + 3, i +.25, str(v))


# Playoff Appearances
sns.barplot(x='Team', y='Made Playoffs', data=vis, palette=colors,
           edgecolor=edges, linewidth=2, ax=ax2, estimator=sum)

ax2.title.set_text('Playoff Appearances')
ax2.set_ylabel('')
ax2.set_xlabel('')

# NFC Championships
sns.barplot(x='Team', y='Won NFC Championship', data=vis, palette=colors,
           edgecolor=edges, linewidth=2, ax=ax3, estimator=sum)

ax3.title.set_text('NFC Championships Won')
ax3.set_ylabel('')
ax3.set_xlabel('')
ax3.set_yticks([0, 1, 2, 3])

# Super Bowls
sns.barplot(x='Team', y='Won Super Bowl', data=vis, palette=colors,
           edgecolor=edges, linewidth=2, ax=ax4, estimator=sum)

ax4.title.set_text('Super Bowls Won')
ax4.set_ylabel('')
ax4.set_xlabel('')
ax4.set_yticks([0, 1, 2])

plt.show()

我得到了我期待的子图,但我不知道如何添加一个“调用”值,显示每个子图中每个条形上方的条形值。

因此,例如,在平均获胜百分比条形图中,牛仔条上方应该有一个“52.6%”,老鹰条上方应该有一个“59.7%”,等等。

y 轴也都是不同的单位。

任何帮助是极大的赞赏!

标签: pythonpandasmatplotlibplotseaborn

解决方案


推荐阅读