Course contentsShow
← Data Science
Lesson 1266 of 2,14532. Visualization with Matplotlib and SeabornFree lesson

Bar Plots: Categorical Comparisons

Build vertical and horizontal bar charts for categorical data, including grouped and stacked variations.

Bar Plots: Categorical Comparisons

What you'll learn: How to build vertical and horizontal bar charts to compare categorical data, including grouped and stacked variations.

The Core Idea

Bar plots display discrete categories on one axis and their corresponding numerical values on the other. Unlike histograms (which bin continuous data), bar plots show distinct categories like product names, regions, or customer segments. You can orient them vertically (columns) or horizontally (bars), and layer them to show multiple dimensions.

Vertical and Horizontal Bars

A vertical bar plot puts categories on the x-axis and values on the y-axis—ideal when category names are short. A horizontal bar plot flips this orientation, making it easier to read long category labels or when you have many categories.

import matplotlib.pyplot as plt

categories = ['Product A', 'Product B', 'Product C']
values = [23, 45, 31]

# Vertical bar plot
plt.bar(categories, values)
plt.title('Vertical Bar Chart')
plt.show()

# Horizontal bar plot
plt.barh(categories, values)
plt.title('Horizontal Bar Chart')
plt.show()

Grouped and Stacked Variations

Grouped bars place bars side-by-side to compare multiple series (e.g., sales by region and quarter). Stacked bars layer series on top of each other, showing part-to-whole relationships alongside totals.

import numpy as np

x = np.arange(3)
series1 = [23, 45, 31]
series2 = [18, 37, 28]

# Grouped
plt.bar(x - 0.2, series1, width=0.4, label='Q1')
plt.bar(x + 0.2, series2, width=0.4, label='Q2')
plt.xticks(x, categories)
plt.legend()
plt.show()

# Stacked
plt.bar(categories, series1, label='Q1')
plt.bar(categories, series2, bottom=series1, label='Q2')
plt.legend()
plt.show()

Key Takeaway: Bar plots excel at comparing categorical data—use vertical or horizontal orientation for readability, grouped bars to compare across dimensions, and stacked bars to show composition and totals together.