如何在 Seaborn 中使用 Matplotlib 在條形圖頂部新增百分比?


要將百分比新增到 Seaborn 中條形圖頂部,我們可以執行以下步驟 -

  • 使用 Seaborn 建立列表 x、y百分比 以進行繪圖。

  • 使用 barplot,顯示條形圖的點估計和置信區間。儲存返回的軸。

  • 從返回軸(在步驟 2 中)找到斑塊。

  • 迭代斑塊(在步驟 3 中返回)。

  • 從斑塊找到 xy 以將百分比值放在條形圖頂部。

  • 要顯示該圖形,請使用 show() 方法。

示例

import matplotlib.pyplot as plt
import seaborn as sns
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = ['A', 'B', 'C', 'D', 'E']
y = [1, 3, 2, 0, 4]
percentage = [10, 30, 20, 0, 40]
ax = sns.barplot(x=x, y=y, palette='PuBuGn_r')
patches = ax.patches
for i in range(len(patches)):
   x = patches[i].get_x() + patches[i].get_width()/2
   y = patches[i].get_height()+.05
   ax.annotate('{:.1f}%'.format(percentage[i]), (x, y), ha='center')
plt.show()

輸出

更新日期:2021 年 5 月 6 日

6 千次以上瀏覽

開啟您的 職業生涯

完成課程以獲取認證

開始
廣告
© . All rights reserved.