Python matplotlib multiple bars

MatplotlibServer Side ProgrammingProgramming

We can use a user-defined method, autolabel, to annotate the axis value. Before that, we can initialize the fig and ax using plt.subplots() method.


  • Create lists, labels, men_means, and women_means with different data elements.

  • Return evenly spaced values within a given interval, using numpy.arrange() method.

  • Set the width variable i.e., width=0.35.

  • Create fig and ax variables using subplots method, where default nrows and ncols are 1.

  • The bars are positioned at *x* with the given *align*\ment. Their dimensions are given by *height* and *width*. The vertical baseline is *bottom* (default 0), so create rect1 and rect2 using method.

  • Set the Y-axis label using plt.ylabel() method.

  • Set a title for the axes using set_title() method.

  • Get or set the current tick locations and labels of the X-axis, using set_xticks() method.

  • Set x axis tick labels of the grid using set_xticklabels() method.

  • Place a legend on the figure using legend() method.

  • Annotate created bars(rect1 and rect2) with some label using autolabel() method, that is user-defined method.

  • To show the figure, use the method.


import matplotlib.pyplot as plt
import numpy as np

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))
width = 0.35

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

ax.set_title('Scores by group and gender')

def autolabel(rects):
   for rect in rects:
      height = rect.get_height()
         xy=(rect.get_x() + rect.get_width() / 2, height),
         xytext=(0, 3), # 3 points vertical offset
         textcoords="offset points",
         ha='center', va='bottom')



Updated on 15-Mar-2021 08:41:20