如何在 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