Bar Chart
Python · Data Visualization
Theory
A bar chart compares a number across categories, with bar length proportional to the value. ax.bar(categories, values) draws vertical bars and ax.barh draws horizontal ones, which suit long category names or ranked lists. Bars must start at zero, otherwise their lengths exaggerate differences.
To compare two series per category, draw a grouped chart: put categories at positions x = np.arange(n), then draw one series at x - width/2 and the other at x + width/2. A stacked chart shows parts of a total: draw the first series, then pass bottom=first_series to the second so it starts where the first ends. ax.bar_label(bars) writes the value on each bar. Sorting bars by value usually makes the chart much easier to read.
Why we use it
Comparing amounts across groups (sales by city, headcount by department) is the most common business question, and lengths from a shared baseline are the most accurately read visual encoding.
When to use it
Use bars for categorical comparisons and barh for long labels or rankings. Use grouped bars to compare series side by side and stacked bars when the total matters as much as the parts. For trends over time, a line plot is usually better.
How it works
- Categories and values
- More than one series per category? Yes: Choose grouped or stacked. No: Single ax.bar or ax.barh.
- Is the total the main message? Yes: Stacked: bottom=previous series. No: Grouped: offset x by width/2.
- Sort bars and add ax.bar_label for exact values
- Bar chart that compares categories
Syntax
ax.bar(x, height, width=0.8, color=...)
ax.barh(y, width)
ax.bar(x - w/2, a, w); ax.bar(x + w/2, b, w) # grouped
ax.bar(x, a); ax.bar(x, b, bottom=a) # stacked
ax.bar_label(bars)Example
fig, ax = plt.subplots()
bars = ax.bar(['Jaipur', 'Pune', 'Delhi'], [100, 90, 150])
ax.bar_label(bars)Key points
- Bars must start at zero to be read honestly
- Use barh for long labels or ranked lists
- Grouped bars: shift positions by plus/minus width/2
- Stacked bars: pass bottom= the series below
- Sort bars by value unless the categories have a natural order