Home > Software engineering >  Adding image to legend in matplotlib returns error: AttributeError: 'BarContainer' object
Adding image to legend in matplotlib returns error: AttributeError: 'BarContainer' object

Time:11-25

Given the following code:

import numpy as np
import matplotlib.pyplot as plt
import os, sys

labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 34, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]

x = np.arange(len(labels))  # the label locations
width = 0.35

fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, men_means, width, label='Men')
rects2 = ax.bar(x   width/2, women_means, width, label='Women')

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.legend() # oringinal legend

ax.bar_label(rects1, padding=3)
ax.bar_label(rects2, padding=3)
fig.tight_layout()
plt.savefig('bar.png')

which returns this barplot:

enter image description here

I'd like to replace the legend ['Men', 'Women'] with emojis of enter image description here and enter image description here which are saved in my directory from enter image description here

  • Related