【问题标题】:How to add text values in bar plot seaborn python?如何在条形图 seaborn python 中添加文本值?
【发布时间】:2020-08-21 10:43:31
【问题描述】:

我想用 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)

但我出错了:

【问题讨论】:

  • autolabel(ax.patched) 是什么意思?哪里可以写?
  • @JohanC 我还是错了代码
  • 我试完后报错

标签: python data-visualization seaborn visualization


【解决方案1】:

您需要进行一些更改:

  • 由于您已经创建了ax,因此您需要sns.barplot(..., ax=ax)
  • autolabel() 需要以条形列表作为参数调用。使用 seaborn,您可以通过 ax.patches 获得此列表。
  • for idx,rect in enumerate(ok): 不应使用 ok 而应使用 rects
  • 您不能使用g.textg 是一个数据框,没有 .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.textax.text(..., fontsize=14)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-01
    • 2015-11-22
    • 2020-07-29
    • 2019-11-06
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多