Matplotlib Bar Charts
Compare categorical values with vertical and horizontal bar charts, stacked layouts, and annotations.
Vertical Bar Chart
categories = ["A", "B", "C", "D"]
values = [42, 55, 31, 68]
fig, ax = plt.subplots()
ax.bar(categories, values, color="#2563eb")
ax.set_ylabel("Score")
ax.set_xlabel("Category")Provide descriptive labels and consider sorting to emphasize trends.
Horizontal Bars
Use ax.barh() for long category labels or ranking charts.
ax.barh(categories, values, color="#f97316")
ax.invert_yaxis() # Highest value at the topGrouped Bars
Offset bars to compare multiple series within each category.
import numpy as np
width = 0.35
positions = np.arange(len(categories))
ax.bar(positions - width/2, q1, width, label="Q1")
ax.bar(positions + width/2, q2, width, label="Q2")
ax.set_xticks(positions)
ax.set_xticklabels(categories)
ax.legend()Stacked Bars
Stack values to show composition.
ax.bar(categories, online, label="Online")
ax.bar(categories, retail, bottom=online, label="Retail")
ax.legend()Annotate totals for clarity when categories contain many segments.
Annotating Bars
Add labels to the top of bars with ax.bar_label() (Matplotlib 3.4+).
bars = ax.bar(categories, values)
ax.bar_label(bars, padding=3, fmt="%d")Align style guidelines with the team using documentation delivered to info.studygrid@gmail.com.
Next Steps
Explore histograms to understand distributions of continuous data.
Vertical, Horizontal, and Colored Bars
import matplotlib.pyplot as plt
labels = ["A", "B", "C"]
values = [10, 24, 17]
plt.bar(labels, values, color=["#4299e1", "#48bb78", "#ed8936"])
plt.show()
plt.barh(labels, values) # horizontal bars
plt.show()Use barh when category labels are long — horizontal bars keep them readable.
Try It Yourself
Exercise: Make a bar chart of three products and their sales.
Show solution
import matplotlib.pyplot as plt
plt.bar(["Pens", "Books", "Bags"], [120, 90, 45])
plt.ylabel("units sold")
plt.show()Key Takeaways
barfor vertical,barhfor horizontal bars.- Bars compare quantities across categories.
- Pass a list of colors to style each bar.
📘 Real-World Deep Dive
Knowing <strong>Matplotlib Bars (Matplotlib)</strong> well is what turns Matplotlib from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of Matplotlib Bars that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
import matplotlib.pyplot as plt
cats = ["a", "b", "c"]; vals = [3, 7, 5]
plt.bar(cats, vals, color=["#22c55e", "#ef4444", "#3b82f6"])
plt.title("Counts"); plt.show()Expected Output
(no output)Common mistakes
- Calling
plt.plotwithoutplt.show()in scripts (orplt.savefig) produces no visible output. - Passing mismatched array shapes to
plt.plot(x, y)raises a uselessValueError— verify shapes withx.shapeandy.shapefirst. - Mixing
numpy.float64withpandas.Seriesis OK, but mixingnumpy.datetime64with Pythondatetime.dateneeds an explicit cast. - Treating Matplotlib Bars as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- For large scatter plots use
plt.scatter(..., s=1, rasterised=True)or switch todatashader. - Use the
aggbackend on web services:import matplotlib; matplotlib.use("Agg"). - Plot once and reuse the figure: avoid embedding Matplotlib into tight Python loops without an explicit
clear(). - When working with Matplotlib, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.