A bar chart compares amounts across categories: sales by city, students by course, votes by option. Each bar's length shows the value, and people compare lengths very accurately, which makes bar charts one of the clearest charts there is.
This lesson covers vertical and horizontal bars, sorting, labelling bars with their values, grouped and stacked bars, and the rules that keep bar charts honest.
A basic bar chart
import matplotlib.pyplot as plt
import numpy as np
courses = ["Python", "Web dev", "Data science", "DSA", "DevOps"]
students = [320, 210, 275, 190, 95]
fig, ax = plt.subplots()
ax.bar(courses, students)
ax.set_title("Students per course")
ax.set_ylabel("Students")
plt.show()
ax.bar(categories, values) is all you need. Options include color, width (default 0.8), edgecolor and alpha.
Sort the bars
Unless the categories have a natural order (months, age groups, ratings), sort the bars by value. Readers instantly see the ranking:
order = np.argsort(students)[::-1] # largest first
sorted_courses = [courses[i] for i in order]
sorted_students = [students[i] for i in order]
fig, ax = plt.subplots()
ax.bar(sorted_courses, sorted_students, color="tab:purple")
ax.set_title("Python is the most popular course")
ax.set_ylabel("Students")
plt.show()
With pandas this is shorter: s.sort_values(ascending=False).plot.bar().
Horizontal bars for long names
When category names are long or there are many of them, turn the chart sideways with ax.barh, so the labels are easy to read:
fig, ax = plt.subplots()
ax.barh(sorted_courses[::-1], sorted_students[::-1], color="tab:purple")
ax.set_title("Students per course")
ax.set_xlabel("Students")
plt.show()
barh draws the first item at the bottom, so reverse the lists ([::-1]) to put the biggest bar on top.
Label bars with their values
ax.bar_label writes each bar's value on it, so readers don't have to estimate from the axis:
fig, ax = plt.subplots()
bars = ax.bar(sorted_courses, sorted_students, color="tab:purple")
ax.bar_label(bars, padding=3)
ax.set_title("Students per course")
ax.spines[["top", "right"]].set_visible(False)
plt.show()
Use fmt to format the numbers, for example fmt="₹{:,.0f}" for rupees or fmt="%.1f%%" for percentages. With values on the bars, you can often remove the y-axis entirely for a cleaner look.
Highlight one bar
To draw attention to one category, colour it differently and keep the rest neutral:
colours = ["tab:orange" if c == "DevOps" else "lightgrey" for c in sorted_courses]
fig, ax = plt.subplots()
ax.bar(sorted_courses, sorted_students, color=colours)
ax.set_title("DevOps has the fewest students: time to promote it?")
plt.show()
Grouped bars
To compare two or more series across the same categories, place bars side by side. Matplotlib needs you to shift each series a little along the x-axis:
years = ["2023", "2024", "2025"]
online = [120, 180, 260]
offline = [200, 190, 170]
x = np.arange(len(years)) # 0, 1, 2
width = 0.38
fig, ax = plt.subplots()
ax.bar(x - width / 2, online, width, label="Online")
ax.bar(x + width / 2, offline, width, label="Offline")
ax.set_xticks(x, years)
ax.set_title("Online enrolments overtook offline")
ax.set_ylabel("Students")
ax.legend()
plt.show()
x - width / 2 and x + width / 2 put the pairs either side of each year's position, and set_xticks(x, years) labels the positions with the years. With pandas, df.plot.bar() on a DataFrame does all of this automatically.
Stacked bars
Stacked bars show a total and its parts together. Each segment starts where the previous one ended, using bottom:
fig, ax = plt.subplots()
ax.bar(years, offline, label="Offline")
ax.bar(years, online, bottom=offline, label="Online")
ax.set_title("Total enrolments by mode")
ax.set_ylabel("Students")
ax.legend()
plt.show()
Stacked bars make the total and the bottom segment easy to compare. The upper segments don't share a baseline, so they're harder to compare. If comparing the parts matters most, use grouped bars.
Rules for honest bar charts
- Always start the value axis at zero. A bar's length is its value; cutting the axis at 150 makes 200 look twice as big as 175. Matplotlib starts bars at zero by default; don't override it with
set_ylim(150, ...). - Use one colour unless colour means something (a highlight, or different series).
- Keep bars wider than the gaps between them.
- Avoid 3D bars and shadows: they distort lengths.
- For a trend over many time points, use a line chart instead.
Practice
- Make a horizontal bar chart of these favourite languages, sorted, with values on the bars: Python 45, JavaScript 30, Java 15, C++ 10.
Show the answer
langs = ["C++", "Java", "JavaScript", "Python"] # smallest first for barh
votes = [10, 15, 30, 45]
fig, ax = plt.subplots()
bars = ax.barh(langs, votes)
ax.bar_label(bars, padding=3)
plt.show()
- Add a third series,
hybrid = [10, 40, 90], to the grouped bar chart.
Show the answer
Use a narrower width and three offsets:
width = 0.27
series = [(-width, online, "Online"), (0, offline, "Offline"), (width, [10, 40, 90], "Hybrid")]
fig, ax = plt.subplots()
for offset, values, label in series:
ax.bar(x + offset, values, width, label=label)
ax.set_xticks(x, years)
ax.legend()
plt.show()
- A chart shows bars for 98, 99 and 100 with the y-axis starting at 97. What's wrong?
Show the answer
Cutting the axis makes 100 look three times taller than 98, though it's only about 2% bigger. Bar charts must start at zero. If small differences matter, show the change itself, or use a dot plot.
Interview questions
Why must bar charts start at zero?
Readers judge bars by length, so the length must be proportional to the value. A truncated axis exaggerates differences and misleads.
When would you use a horizontal bar chart?
When category labels are long, when there are many categories, or for rankings, where a sorted list reads naturally from top to bottom.
Grouped vs stacked bar charts?
Grouped bars compare each series across categories directly, since all bars share a baseline. Stacked bars show totals and composition, but only the bottom segment and the total are easy to compare.
What to learn next
- Show relationships between numbers with scatter plots in Matplotlib.
- Show the shape of one variable with histograms in Matplotlib.