亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在條形圖 seaborn python 中添加文本值?

如何在條形圖 seaborn python 中添加文本值?

POPMUISE 2023-06-13 19:16:41
我想用 seaborn 進行可視化并添加文本。這是我的代碼:# barplot price by body-stylefig, 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)但我出錯了:
查看完整描述

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()

http://img1.sycdn.imooc.com//64885045000154ce14450605.jpg

PS:您可以通過參數將文本的字體大小更改為ax.textax.text(..., fontsize=14)



查看完整回答
反對 回復 2023-06-13
  • 1 回答
  • 0 關注
  • 187 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號