BarContainer' object has no attribute 'get_height'
时间: 2023-06-22 17:31:32 浏览: 305
抱歉,我之前的回答有误。在 `seaborn` 库中,`barplot` 函数返回的是一个 `AxesSubplot` 对象,而不是一个 `BarContainer` 对象。因此,需要使用 `patches` 属性来获取每个柱子的信息,然后使用 `get_height()` 函数获取每个柱子的高度。
具体的代码如下:
```python
import seaborn as sns
# 加载数据集
tips = sns.load_dataset("tips")
# 绘制柱状图
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` 是相对于偏移量的像素坐标。
运行上面的代码,即可在 `seaborn` 库中的柱状图上添加数据标签。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)