如何在 Seaborn 中使用 Matplotlib 在條形圖頂部新增百分比?
要將百分比新增到 Seaborn 中條形圖頂部,我們可以執行以下步驟 -
使用 Seaborn 建立列表 x、y 和 百分比 以進行繪圖。
使用 barplot,顯示條形圖的點估計和置信區間。儲存返回的軸。
從返回軸(在步驟 2 中)找到斑塊。
迭代斑塊(在步驟 3 中返回)。
從斑塊找到 x 和 y 以將百分比值放在條形圖頂部。
要顯示該圖形,請使用 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()輸出

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP