1 回答

TA貢獻1836條經驗 獲得超5個贊
你需要做一些改變:
由于您已經創建了
ax
,因此您需要sns.barplot(..., ax=ax)
.autolabel()
需要以柱列表作為參數調用。使用 seaborn,您可以通過ax.patches
.for idx,rect in enumerate(ok):
不應該使用ok
但是rects
。你不能使用
g.text
。g
是一個數據框,沒有功能.text
。你需要ax.text
。用作
g['price'].unique().tolist()[idx]
要打印的文本與繪制的條形圖沒有任何關系。你可以改用height
。
這是一些帶有玩具數據的測試代碼:
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
fig, ax = plt.subplots(figsize=(12, 8))
g = data[['body-style','price']].groupby(by = 'body-style').sum().reset_index().sort_values(by='price')
x = g['body-style']
y = g['price']
# x = list('abcdefghij')
# y = np.random.randint(20, 100, len(x))
sns.barplot(x, y, ci=None, ax=ax)
ax.set_title('Price By Body Style')
def autolabel(rects):
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width() / 2., 0.2 * height,
height,
ha='center', va='bottom', rotation=90, color='white')
autolabel(ax.patches)
plt.show()
PS:您可以通過參數將文本的字體大小更改為ax.text
: ax.text(..., fontsize=14)
。
添加回答
舉報