如何在条形图seaborn python中添加文本值?
我想用seaborn进行可视化分析并添加文本。这是我的代码:如何在条形图seaborn python中添加文本值?,python,data-visualization,seaborn,visualization,Python,Data Visualization,Seaborn,Visualization,我想用seaborn进行可视化分析并添加文本。这是我的代码: # barplot price by body-style 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'] ok = sn
# barplot price by body-style
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']
ok = sns.barplot(x,y, ci = None)
ax.set_title('Price By Body Style')
def autolabel(rects):
for idx,rect in enumerate(ok):
height = rect.get_height()
g.text(rect.get_x() + rect.get_width()/2., 0.2*height,
g['price'].unique().tolist()[idx],
ha='center', va='bottom', rotation=90)
autolabel(ok)
但我还是犯了一个错误:
您需要做一些更改:
- 由于您已经创建了
,因此需要ax
sns.barplot(…,ax=ax)
需要使用条列表作为参数进行调用。使用seaborn,您可以通过autolabel()
获得此列表ax.patches
不应使用对于idx,枚举中的rect(确定):
,而应使用ok
rects
- 您不能使用
g.text
是一个数据帧,没有g
功能。您需要.text
ax.text
- 使用
作为要打印的文本与打印的条形图没有任何关系。您可以使用g['price'].unique().tolist()[idx]
高度
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)
自动标签(ax.patched)是什么意思?我在哪里可以写它?@JohanC我还是错了代码我试了试,结果出错了