Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在条形图seaborn python中添加文本值?_Python_Data Visualization_Seaborn_Visualization - Fatal编程技术网

如何在条形图seaborn python中添加文本值?

如何在条形图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

我想用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 = 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)
  • autolabel()
    需要使用条列表作为参数进行调用。使用seaborn,您可以通过
    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我还是错了代码我试了试,结果出错了