R
Rishtaara
Python: Zero to Professional
Lesson 22 of 40Article14 min

Matplotlib Bars, Histograms & Pie Charts

plt.bar(categories, values) compares discrete groups — sales by region, votes by party.

Matplotlib Bars

plt.bar(categories, values) compares discrete groups — sales by region, votes by party.

plt.barh() is horizontal bars when labels are long.

Real-life example: Bar charts are city skylines — taller buildings mean bigger values.

Bar chart
import matplotlib.pyplot as plt

courses = ["Python", "JS", "SQL"]
students = [120, 95, 80]
plt.bar(courses, students)
plt.show()

Matplotlib Histograms

plt.hist(data, bins=10) shows frequency distribution — ages, exam scores, response times.

Choose bin count to balance detail vs noise.

Real-life example: A histogram is sorting mail into slots — see which score ranges pile up highest.

Histogram
import matplotlib.pyplot as plt

scores = [62, 71, 75, 80, 82, 88, 91, 95]
plt.hist(scores, bins=5)
plt.xlabel("Score")
plt.ylabel("Count")
plt.show()

Matplotlib Pie Charts

plt.pie(sizes, labels=labels, autopct='%1.1f%%') shows parts of a whole.

Best for few categories — too many slices become unreadable.

Real-life example: Pie charts are pizza slices — each slice shows who ate what share.

Pie chart
import matplotlib.pyplot as plt

labels = ["Python", "JS", "Other"]
sizes = [45, 35, 20]
plt.pie(sizes, labels=labels, autopct="%1.0f%%")
plt.show()