1

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

0

1 Answer 1

5
  • 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

Sign up to request clarification or add additional context in comments.

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.