How to annotate a bar plot and add a custom legend

Question:

I am trying to draw a Bar chart that looks like the one below, I am not sure how to set a percentage value in each column top, and a legend at the right side. My code snippets below. It’s working, however it’s missing the percentage value and legend.

import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt

objects = ('18-25', '26-30', '31-40', '40-50')
y_pos = np.arange(len(objects))
performance = [13, 18, 16, 3]
width = 0.35  # the width of the bars
plt.bar(y_pos, performance, align='center', alpha=0.5, color=('red', 'green', 'blue', 'yellow'))
plt.xticks(y_pos, objects)
plt.ylabel('%User', fontsize=16)
plt.title('Age of Respondents', fontsize=20)
width = 0.35

plt.show()

enter image description here

Asked By: Mamunur Rashid

||

Answers:

  • The legend colors were slightly different than the plot colors because alpha=0.5, which has been removed.
  • imagecolorpicker.com was used to select the correct blue and green.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Patch

color = ('red', '#00b050', '#00b0f0', 'yellow')
objects = ('18-25', '26-30', '31-40', '40-50')
y_pos = np.arange(len(objects))
performance = [13, 18, 16, 3]
width = 0.35  # the width of the bars
plt.bar(y_pos, performance, align='center', color=color)
plt.xticks(y_pos, objects)
plt.ylim(0, 20)  # this adds a little space at the top of the plot, to compensate for the annotation
plt.ylabel('%User', fontsize=16)
plt.title('Age of Respondents', fontsize=20)

# map names to colors
cmap = dict(zip(performance, color))

# create the rectangles for the legend
patches = [Patch(color=v, label=k) for k, v in cmap.items()]

# add the legend
plt.legend(title='Number of Trips', labels=objects, handles=patches, bbox_to_anchor=(1.04, 0.5), loc='center left', borderaxespad=0, fontsize=15, frameon=False)

# add the annotations
for y, x in zip(performance, y_pos):
    plt.annotate(f'{y}%n', xy=(x, y), ha='center', va='center')

enter image description here

Annotation Resources – from matplotlib v3.4.2

Answered By: Trenton McKinney
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.