5 min read min read
Bar Charts
Learn to compare categories with bar charts
Bar Charts
When to Use Bar Charts?
Bar charts compare categories:
- Sales by product
- Population by country
- Votes by candidate
Basic Bar Chart
code.py
import matplotlib.pyplot as plt
products = ['A', 'B', 'C', 'D']
sales = [100, 150, 80, 120]
fig, ax = plt.subplots()
ax.bar(products, sales)
ax.set_title('Sales by Product')
plt.show()Horizontal Bar Chart
code.py
ax.barh(products, sales) # barh = horizontalBetter when category names are long.
Change Bar Color
code.py
ax.bar(products, sales, color='green')Different Colors per Bar
code.py
colors = ['red', 'blue', 'green', 'orange']
ax.bar(products, sales, color=colors)Add Data Labels
code.py
fig, ax = plt.subplots()
bars = ax.bar(products, sales)
# Add value on top of each bar
for bar, value in zip(bars, sales):
ax.text(bar.get_x() + bar.get_width()/2, bar.get_height(),
str(value), ha='center', va='bottom')
plt.show()Grouped Bar Chart
Compare multiple series:
code.py
import matplotlib.pyplot as plt
import numpy as np
categories = ['A', 'B', 'C']
sales_2023 = [100, 150, 80]
sales_2024 = [120, 140, 100]
x = np.arange(len(categories))
width = 0.35
fig, ax = plt.subplots()
ax.bar(x - width/2, sales_2023, width, label='2023')
ax.bar(x + width/2, sales_2024, width, label='2024')
ax.set_xticks(x)
ax.set_xticklabels(categories)
ax.legend()
plt.show()Stacked Bar Chart
code.py
categories = ['Q1', 'Q2', 'Q3', 'Q4']
product_a = [20, 25, 30, 35]
product_b = [15, 20, 18, 22]
fig, ax = plt.subplots()
ax.bar(categories, product_a, label='Product A')
ax.bar(categories, product_b, bottom=product_a, label='Product B')
ax.legend()
plt.show()Change Bar Width
code.py
ax.bar(products, sales, width=0.5) # default is 0.8Add Edge Color
code.py
ax.bar(products, sales, color='lightblue', edgecolor='black')Complete Example
code.py
import matplotlib.pyplot as plt
# Data
departments = ['Sales', 'IT', 'HR', 'Marketing']
employees = [25, 15, 10, 20]
colors = ['#3498db', '#2ecc71', '#e74c3c', '#f39c12']
fig, ax = plt.subplots(figsize=(10, 6))
bars = ax.bar(departments, employees, color=colors, edgecolor='black')
# Add labels on bars
for bar, emp in zip(bars, employees):
ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5,
str(emp), ha='center', fontsize=12)
ax.set_ylabel('Number of Employees')
ax.set_title('Employees by Department')
ax.set_ylim(0, 30)
plt.show()Key Points
- bar() for vertical bars
- barh() for horizontal bars
- Use color to change bar colors
- Use width to change bar width
- Grouped bars: offset x positions
- Stacked bars: use bottom parameter
What's Next?
Learn histograms for showing distribution of data.