seaborn添加数据标签
时间: 2023-08-02 14:29:22 浏览: 94
可以使用`seaborn`中的`sns.barplot()`函数来添加数据标签,具体步骤如下:
1. 导入`seaborn`库和数据集
```python
import seaborn as sns
tips = sns.load_dataset("tips")
```
2. 使用`sns.barplot()`函数绘制柱状图,并将数据标签添加到每个柱子上
```python
ax = sns.barplot(x="day", y="total_bill", data=tips)
for p in ax.patches:
ax.annotate("%.2f" % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()),
ha='center', va='center', fontsize=11, color='gray', xytext=(0, 5),
textcoords='offset points')
```
在上面的代码中,`ax.patches`获取每个柱子的信息,`p.get_x()`和`p.get_width()`获取柱子的位置和宽度,`p.get_height()`获取柱子的高度,`ax.annotate()`函数在每个柱子上添加数据标签。
在`ax.annotate()`函数中,`"%.2f" % p.get_height()`表示保留两位小数的柱子高度,`xytext=(0, 5)`表示数据标签相对于柱子顶部偏移5个像素,`textcoords='offset points'`表示`xytext`是相对于偏移量的像素坐标。
运行上面的代码,即可在柱状图上添加数据标签。
阅读全文
相关推荐
















