Bar charts compare values across categories, such as sales per region or students per course.
Prerequisites
Vertical Bar Chart
import matplotlib.pyplot as plt
courses = ['Python', 'ML', 'DL', 'NLP']
students = [120, 95, 60, 45]
fig, ax = plt.subplots()
bars = ax.bar(courses, students, color='steelblue')
ax.set_title('Students per Course')
ax.set_ylabel('Students')
ax.bar_label(bars)
plt.show()
Explanation: ax.bar(categories, values) draws the bars. bar_label writes the value on top of each bar.
Horizontal Bar Chart
fig, ax = plt.subplots()
ax.barh(courses, students, color='orange')
ax.invert_yaxis()
plt.show()
Explanation: Horizontal bars are easier to read when category names are long. invert_yaxis puts the first item on top.
Grouped Bars
import numpy as np
x = np.arange(len(courses))
w = 0.35
boys = [70, 50, 35, 20]
girls = [50, 45, 25, 25]
fig, ax = plt.subplots()
ax.bar(x - w/2, boys, w, label='Boys')
ax.bar(x + w/2, girls, w, label='Girls')
ax.set_xticks(x, courses)
ax.legend()
plt.show()
Explanation: Shift each group left and right by half the bar width so they sit side by side.
Stacked Bars
fig, ax = plt.subplots()
ax.bar(courses, boys, label='Boys')
ax.bar(courses, girls, bottom=boys, label='Girls')
ax.legend()
plt.show()
Explanation: bottom= starts the second bar where the first ends.
Common Errors
| Problem | Cause and fix |
|---|---|
| Labels overlap | Use barh, or rotate: plt.xticks(rotation=45, ha=’right’). |
Practice Exercises
- Plot marks of 5 students and color bars below 40 in red.
- Make a grouped bar chart of 2025 vs 2026 sales by quarter.
Interview Questions
Q: When should you use a bar chart instead of a line chart?
For comparing separate categories, not continuous trends.
Summary
Use ax.bar or ax.barh, offset positions for grouped bars, bottom= for stacked bars, and bar_label for values.
Machine Learning Tutorials, Courses and Certifications