How to plot multiple column barplots with Matplotlib?

Follow this tutorial to create a multiple column bar plots with Python and Matplotlib.

Step 1: Import Matplotlib

First off, import the matplotlib package into your Jupyter Notebook / Google Colab, PyCharm, VSCode or other Python development environments you might be using.

import matplotlib.pyplot as plt

Step 2: Acquire your dataset

In this example, we will just define a few Python lists and plot their contents. We will plot the number of candidates vs hired employees for three random offices.

language = ['Javascript', 'Javascript', 'R', 'Javascript', 'Python', 'Python']
candidates = [143, 143, 146, 125, 173, 132]
hired = [12, 15, 17, 13, 12, 11]

Step 3: Draw a stacked bar chart

The pandas and Seaborn libraries offer very simple ways to create a bar plot with multiple stacked columns. In matplotlib is a bit more elaborated. Here’s the code:

fig, ax = plt.subplots() #1

ax.bar(x = office, height = candidates, color  = 'navy', label = 'Candidates'); #2
ax.bar(x = office, height = hired, color  = 'gold', label = 'Hired'); #3
ax.legend(); #4

Explanation

  • In row # 1, we define a figure (container) and a chart.
  • We then populate the list of candidates by office (these are the “navy” columns in the chart).
  • We then populate the list of hired employees by office (there are the “yellow” columns in the chart).
  • Last, we show the chart with the legend.

Step 4: Plot multiple column charts

In the next example, we will create multiple plots. In the first we will present the number of candidates and in the second the number of hires.

fig, ax = plt.subplots(1,2) #1

ax[0].bar(x = office, height = candidates, color = 'Navy')
ax[1].bar(x = office, height = hired, color  = 'gold')
ax[0].set_title('Number of candidates') 
ax[1].set_title('Number of hires');

Explanation

  • The code is very similar to the one offered in the previous step. The only addition is that in Row #1, instead of defining one chart, we define two charts showing up side by side.

Related learning

How to plot two or more charts with Matplotlib and Seaborn?