sns.barplot的柱状图上方显示数值
时间: 2023-10-26 15:16:45 浏览: 171
要在 `sns.barplot` 的柱状图上方显示数值,可以使用 `annotate` 方法来添加文本标签。以下是一个例子:
```python
import seaborn as sns
import matplotlib.pyplot as plt
# 加载示例数据
tips = sns.load_dataset("tips")
# 绘制柱状图
ax = sns.barplot(x="day", y="total_bill", data=tips)
# 在每个柱子上方添加数值标签
for p in ax.patches:
ax.annotate(format(p.get_height(), '.2f'),
(p.get_x() + p.get_width() / 2., p.get_height()),
ha = 'center', va = 'center',
xytext = (0, 10),
textcoords = 'offset points')
# 显示图形
plt.show()
```
在这个例子中,我们加载了 Seaborn 库中的 `tips` 数据集,并使用 `sns.barplot` 来绘制一张柱状图。然后,我们使用 `annotate` 方法在每个柱子上方添加数值标签。其中,
- `format(p.get_height(), '.2f')` 用于格式化数值为带有两位小数的字符串;
- `(p.get_x() + p.get_width() / 2., p.get_height())` 是标签的位置;
- `ha = 'center', va = 'center'` 是标签的水平和垂直对齐方式;
- `xytext = (0, 10)` 是标签文本相对于标签位置的偏移量;
- `textcoords = 'offset points'` 是标签文本的坐标系。
最后,我们使用 `plt.show()` 方法显示图形。
阅读全文
相关推荐















