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.
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
- 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.bar(x = office, height = candidates, color = 'Navy') ax.bar(x = office, height = hired, color = 'gold') ax.set_title('Number of candidates') ax.set_title('Number of hires');
- 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.