Thursday , December 3 2026
Bar Plot using Matplotlib

Bar Plot using Matplotlib

Updated: 28 November 2026Level: BeginnerReading time: about 7 minutesMatplotlib 3.8+

Bar charts compare values across categories, such as sales per region or students per course.

Prerequisites

Introduction to Matplotlib.

Vertical Bar Chart

Example
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

Example
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

Example
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

Example
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

  1. Plot marks of 5 students and color bars below 40 in red.
  2. 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.

Next: Pie Plot · Histogram

About Machine Learning

Check Also

Exploratory Data Analysis (EDA) in Python: Step-by-Step Checklist

A step-by-step EDA checklist in pandas with tested outputs: shape, missing values, describe, value counts, groupby, correlations and charts.