0

i want visualyze with seaborn and add the text. this my code:

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

but i go error:

enter image description here

3
  • what does it means autolabel(ax.patched)? where can i write it? Commented Aug 21, 2020 at 11:51
  • @JohanC i still wrong code Commented Aug 21, 2020 at 11:52
  • i finish try it and got an error Commented Aug 21, 2020 at 11:58

1 Answer 1

3

You need a few changes:

  • As you already created the ax, you need sns.barplot(..., ax=ax).
  • autolabel() needs to be called with the list of bars as argument. With seaborn you get this list via ax.patches.
  • for idx,rect in enumerate(ok): shouldn't use ok but rects.
  • You can't use g.text. g is a dataframe and doesn't have a .text function. You need ax.text.
  • Using g['price'].unique().tolist()[idx] as the text to print doesn't have any relationship with the plotted bars. You could use height instead.

Here is some test code with toy data:

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

example plot

PS: You can change the fontsize of the text via a parameter to ax.text: ax.text(..., fontsize=14).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.