Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Labeling horizontal barplot with values in Seaborn

I have a horizontal barplot, for example, a simplified version of the example from the seaborn documentation:

import seaborn as sns
import matplotlib.pyplot as plt

f, ax = plt.subplots(figsize=(6, 15))

crashes = sns.load_dataset("car_crashes").sort_values("total", ascending=False)

sns.barplot(x="total", y="abbrev", data=crashes,
            label="Total", color="b")

ax.set(xlim=(0, 24), ylabel="",
       xlabel="Automobile collisions per billion miles")

plt.show()

How can I get the bars labeled with the value for each bar?

I tried this approach for vertical bars (How to add percentages on top of bars in seaborn), but it doesn't seem to work. Changing height to width doesn't have the effect I assumed it would.

for p in ax.patches:
    height = p.get_width()
    ax.text(p.get_y()+p.get_height()/2.,
            height + 3,
            '{:1.2f}'.format(height),
            ha="center")

I'm assuming the horizontal plot works differently?

like image 521
max Avatar asked Apr 13 '18 15:04

max


People also ask

How to plot values in Seaborn barplot with bar?

Syntax: seaborn.barplot (data, x=None, y=None, hue=None, data=None, order=None, orient=None, color=None, palette=None, saturation=0.75,errwidth) In seaborn barplot with bar, values can be plotted using sns.barplot () function and the sub-method containers returned by sns.barplot ().

How to get the value of a bar in a barplot?

This plot object is stored in a variable. The plot object has a method called containers that would list the properties of each bar. Now, pass the container object to the bar_label function. This will extract and display the bar value in the bar plot.

How do I create a horizontal barplot in R?

#create horizontal barplotp = sns.barplot(x="tip", y="day", data=data, ci=None) #show values on barplotshow_values(p, "h", space=0) Note that the larger the value you use for space, the further away the labels will be from the bars.

What are the Seaborn components used?

seaborn components used: set_theme (), load_dataset (), set_color_codes (), barplot (), set_color_codes (), barplot (), despine ()


1 Answers

Got it, thanks to @ImportanceOfBeingErnest

This worked for me

for p in ax.patches:
    width = p.get_width()    # get bar length
    ax.text(width + 1,       # set the text at 1 unit right of the bar
            p.get_y() + p.get_height() / 2, # get Y coordinate + X coordinate / 2
            '{:1.2f}'.format(width), # set variable to display, 2 decimals
            ha = 'left',   # horizontal alignment
            va = 'center')  # vertical alignment
like image 185
max Avatar answered Nov 14 '22 21:11

max