Jane Borges
Jane Borges

Reputation: 592

Building charts with value_counts

I have the following dataframe:

       df_Mechanics = pd.DataFrame({'Car Plate End': [749, 749, 749,749, 749, 
                                                      749, 749, 749, 749, 49],
                     'Car Model': ['Mustang', 'Mustang', 'Mustang', 'Mustang', 'Mustang',
                                   'Mustang', 'Mustang', 'Mustang', 'Mustang', 'Mustang'],
                     'Replaced part': ['brake pad', 'wheel', 'engine', 'engine', 'engine',
                                       'wheel', 'engine','engine', 'engine', 'engine']
                    })

       print(df_Mechanics)
       Car Plate End    Car Model   Replaced part
            749           Mustang   brake pad
            749           Mustang   wheel
            749           Mustang   engine
            749           Mustang   engine
            749           Mustang   engine
            749           Mustang   wheel
            749           Mustang   engine
            749           Mustang   engine
            749           Mustang   engine
            749           Mustang   engine

I would like to plot a probability plot of parts that have been used. So, I did the following:

       prob = df_Mechanics['Replaced part'].value_counts(normalize=True)



       threshold = 0.05
       mask = prob > threshold

       tail_prob = prob.loc[~mask].sum()
       prob = prob.loc[mask]
       prob.plot(kind='bar')
       plt.xticks(rotation=25)
       plt.show()

The graph is as expected. But I would like to perfect your designer.

I found a very good example at this link: https://matplotlib.org/3.2.1/gallery/statistics/barchart_demo.html

I'm having trouble understanding.

I would like to make my graph horizontal, that the x-axis is up to 100% and that the probabilities appear in the bars. Thanks for listening.

Upvotes: 0

Views: 122

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150735

You can use barh instead of bar for horizontal bar, then extract the patches to annotate with ax.text:

# replace prob.plot(...) with the following
ax = prob.plot(kind='barh')

# loop through the bars
for patch in ax.patches:
    # extract bar's information
    x = patch.get_width()
    bar_width=patch.get_height()
    y = patch.get_y()

    # annotate the bar
    ax.text(x-.05, y+bar_width/2, f'{x:.0%}',
            verticalalignment='center',
            color='white')

Output:

enter image description here

Upvotes: 1

Related Questions