1

I'm trying to annotate precentage in horizontal barplot with matplotlib. The problem is that when I try to add the precentage annotation I get error:

"module 'matplotlib.pyplot' has no attribute 'patches'

This is how I try to create the chart:

import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
%matplotlib inline


sns.set(style="whitegrid")
#sns.set_color_codes("Spectral")



plt.figure(2, figsize=(20,15))
the_grid = GridSpec(2, 2)

plt.subplot(the_grid[0, 1],  title='Original Dataset')
sns.barplot(x='count',y='land_cover_specific', data=df, palette='Spectral')
plt.xlabel('Count')
plt.ylabel('Land cover')

total = len(original)
print(total)

for p in plt.patches:
        percentage = '{:.1f}%'.format(100 * p.get_width()/total)
        x = p.get_x() + p.get_width() + 0.02
        y = p.get_y() + p.get_height()/2
        plt.annotate(percentage, (x, y))

plt.show()

I get the bar plot but I do not get the annotation due to this error. enter image description here

My end goal: to add teh rpecentage of each bar count out of the total

2 Answers 2

3

I think you only need to change :

sns.barplot(x='count',y='land_cover_specific', data=df, palette='Spectral')

to:

ax = sns.barplot(x='count',y='land_cover_specific', data=df, palette='Spectral')

and

for p in plt.patches:

to:

for p in ax.patches:
Sign up to request clarification or add additional context in comments.

Comments

1
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
%matplotlib inline


sns.set(style="whitegrid")
#sns.set_color_codes("Spectral")



plt.figure(2, figsize=(20,15))
the_grid = GridSpec(2, 2)

plt.subplot(the_grid[0, 1],  title='Original Dataset')
horizontal = sns.barplot(x='count',y='land_cover_specific', data=df, palette='Spectral')
plt.xlabel('Count')
plt.ylabel('Land cover')


total = len(original)
# print(total)

# for p in plt.patches:
#         percentage = '{:.1f}%'.format(100 * p.get_width()/total)
#         x = p.get_x() + p.get_width() + 0.02
#         y = p.get_y() + p.get_height()/2
#         plt.annotate(percentage, (x, y))


def auto_label(horizontal_):
    for index, rectangle in enumerate(horizontal_):
        height = rectangle.get_height()
        width = rectangle.get_width()
        y_value = rectangle.get_y()
        # color is an array containing either hex or rgb values
        # each should map to the color of each in your barchart
        plt.text(width + height/2., y_value, "%d" % 100 * width / total, color=color[index])


auto_label(horizontal)
plt.show()

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.