Matplotlib Grouped Bar Charts in Python

As a Python Matplotlib developer with over seven years of experience, I have found that visualizing data effectively is crucial to understanding complex datasets. One of the most powerful visualization tools I use regularly is the grouped bar chart. It allows me to compare multiple categories side by side clearly and concisely.

When working on data projects, whether analyzing sales across different U.S. states or comparing performance metrics across several machine learning models, grouped bar charts in Python provide an easy way to showcase differences and trends.

In this article, I will share practical methods to create multiple groups in Matplotlib bar charts with full code examples, making it easy for you to apply them in your Python projects.

What is a Grouped Bar Chart in Python Matplotlib?

A grouped bar chart displays bars for different categories grouped along the x-axis. This format is perfect for comparing multiple data series side by side, such as sales figures for several products across various quarters or test scores of students from different schools.

Using Python’s Matplotlib library, you can build these charts with flexibility and customization options. I will walk you through step-by-step methods that I use in my daily work to create clean and informative grouped bar charts.

Method 1: Basic Grouped Bar Chart in Python Matplotlib

The simplest way to create a grouped bar chart is by plotting bars for each group side by side with adjusted positions.

Here’s an example comparing quarterly sales of two products across four U.S. regions:

import matplotlib.pyplot as plt
import numpy as np

# Data for sales in thousands of dollars
regions = ['Northeast', 'Midwest', 'South', 'West']
product_a_sales = [120, 150, 170, 200]
product_b_sales = [100, 140, 160, 180]

x = np.arange(len(regions))  # label locations
width = 0.35  # width of the bars

fig, ax = plt.subplots()
bars1 = ax.bar(x - width/2, product_a_sales, width, label='Product A')
bars2 = ax.bar(x + width/2, product_b_sales, width, label='Product B')

ax.set_ylabel('Sales (in thousands)')
ax.set_title('Quarterly Sales by Product and Region')
ax.set_xticks(x)
ax.set_xticklabels(regions)
ax.legend()

plt.show()

You can see the output in the screenshot below.

Matplotlib Grouped Bar Charts in Python

In this example, I used numpy to position the bars properly. This method is quick and effective for comparing two or more groups in Python.

Method 2: Add Data Labels to Bars for Clarity

Adding labels to each bar helps communicate exact values, especially when presenting to stakeholders.

Here’s how I add labels on top of bars in Matplotlib:

import matplotlib.pyplot as plt
import numpy as np

regions = ['Northeast', 'Midwest', 'South', 'West']
product_a_sales = [120, 150, 170, 200]
product_b_sales = [100, 140, 160, 180]

x = np.arange(len(regions))
width = 0.35

fig, ax = plt.subplots()
bars1 = ax.bar(x - width/2, product_a_sales, width, label='Product A')
bars2 = ax.bar(x + width/2, product_b_sales, width, label='Product B')

ax.set_ylabel('Sales (in thousands)')
ax.set_title('Quarterly Sales by Product and Region')
ax.set_xticks(x)
ax.set_xticklabels(regions)
ax.legend()

def add_labels(bars):
    for bar in bars:
        height = bar.get_height()
        ax.annotate(f'{height}',
                    xy=(bar.get_x() + bar.get_width() / 2, height),
                    xytext=(0, 3),  # offset label above the bar
                    textcoords="offset points",
                    ha='center', va='bottom')

add_labels(bars1)
add_labels(bars2)

plt.show()

You can see the output in the screenshot below.

Matplotlib Grouped Bar Charts Python

This small addition makes the chart much easier to interpret at a glance.

Method 3: Grouped Bar Chart with Multiple Groups in Python

When I need to compare more than two groups, I extend the basic method by increasing the number of bars per group and adjusting their positions accordingly.

Here’s a full example comparing sales for three products:

import matplotlib.pyplot as plt
import numpy as np

regions = ['Northeast', 'Midwest', 'South', 'West']
product_a = [120, 150, 170, 200]
product_b = [100, 140, 160, 180]
product_c = [90, 130, 150, 170]

x = np.arange(len(regions))
width = 0.25

fig, ax = plt.subplots()
bars1 = ax.bar(x - width, product_a, width, label='Product A', color='skyblue')
bars2 = ax.bar(x, product_b, width, label='Product B', color='salmon')
bars3 = ax.bar(x + width, product_c, width, label='Product C', color='lightgreen')

ax.set_ylabel('Sales (in thousands)')
ax.set_title('Quarterly Sales by Product and Region')
ax.set_xticks(x)
ax.set_xticklabels(regions)
ax.legend()

def add_labels(bars):
    for bar in bars:
        height = bar.get_height()
        ax.annotate(f'{height}',
                    xy=(bar.get_x() + bar.get_width() / 2, height),
                    xytext=(0, 3),
                    textcoords="offset points",
                    ha='center', va='bottom')

add_labels(bars1)
add_labels(bars2)
add_labels(bars3)

plt.show()

You can see the output in the screenshot below.

Python Matplotlib Grouped Bar Charts

This method works well when comparing multiple datasets in Python, such as sales, user engagement, or model metrics.

Method 4: Use Pandas with Matplotlib for Grouped Bar Charts

If your data is stored in a pandas DataFrame, you can plot grouped bar charts directly using pandas’ plotting interface, which uses Matplotlib internally.

Here’s how I do it when working with structured data:

import pandas as pd
import matplotlib.pyplot as plt

data = {
    'Region': ['Northeast', 'Midwest', 'South', 'West'],
    'Product A': [120, 150, 170, 200],
    'Product B': [100, 140, 160, 180],
    'Product C': [90, 130, 150, 170]
}

df = pd.DataFrame(data)
df.set_index('Region', inplace=True)

ax = df.plot(kind='bar', figsize=(8,5))
ax.set_ylabel('Sales (in thousands)')
ax.set_title('Quarterly Sales by Product and Region')
plt.xticks(rotation=0)
plt.show()

This approach simplifies your code and is especially useful when working with large datasets in Python.

Tips for Effective Grouped Bar Charts in Python Matplotlib

  • Keep bar width consistent: Adjust width based on the number of groups to avoid clutter.
  • Use contrasting colors: Differentiate groups clearly for better readability.
  • Add legends and labels: Help users understand what each bar represents.
  • Rotate x-axis labels if needed: Prevent overlapping when labels are long.
  • Annotate bars: Show exact values for clarity, especially in presentations.

Creating grouped bar charts in Python Matplotlib is a skill I rely on daily. It helps me visualize comparisons across multiple categories clearly, whether for business data analysis or machine learning model evaluation.

Applying these methods will allow you to build professional and insightful charts tailored to your project needs. The examples I shared are ready to use and easy to customize.

If you want to explore more Python Matplotlib visualization techniques, keep experimenting and refining your charts. Data visualization is a powerful tool to communicate your findings effectively.

Other Python Matplotlib articles you may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.