Matplotlib Bar Charts

Create vertical and horizontal bar charts to compare categorical data

📊 Bar Chart Visualization

Bar charts are perfect for comparing values across different categories. They make it easy to see which categories have the highest or lowest values.


import matplotlib.pyplot as plt

categories = ['A', 'B', 'C', 'D']
values = [23, 45, 56, 78]

plt.bar(categories, values)
plt.xlabel('Categories')
plt.ylabel('Values')
plt.show()
                                    
Vertical
Bars
Horizontal
Bars
Grouped
Comparison

Bar Chart Types

Different styles of bar charts for various data presentations:

📊

Vertical Bars

Standard upward-pointing bars

plt.bar()
📈

Horizontal Bars

Sideways bars for long labels

plt.barh()
📋

Grouped Bars

Multiple series side by side

Multiple calls
🏗️

Stacked Bars

Stack values on top of each other

bottom parameter

🔹 Basic Bar Charts

Create simple vertical and horizontal bar charts

import matplotlib.pyplot as plt

# Sample data
products = ['Product A', 'Product B', 'Product C', 'Product D']
sales = [150, 200, 175, 225]

# Vertical bar chart
plt.figure(figsize=(10, 5))

plt.subplot(1, 2, 1)
plt.bar(products, sales, color='skyblue')
plt.title('Vertical Bar Chart')
plt.xlabel('Products')
plt.ylabel('Sales')
plt.xticks(rotation=45)  # Rotate labels if needed

# Horizontal bar chart
plt.subplot(1, 2, 2)
plt.barh(products, sales, color='lightcoral')
plt.title('Horizontal Bar Chart')
plt.xlabel('Sales')
plt.ylabel('Products')

plt.tight_layout()
plt.show()

# Styled bar chart
plt.figure(figsize=(8, 6))
bars = plt.bar(products, sales, 
               color=['red', 'green', 'blue', 'orange'],
               alpha=0.7,
               edgecolor='black',
               linewidth=1)

plt.title('Styled Bar Chart', fontsize=16, fontweight='bold')
plt.xlabel('Products', fontsize=12)
plt.ylabel('Sales', fontsize=12)
plt.grid(axis='y', alpha=0.3)

# Add value labels on bars
for bar, value in zip(bars, sales):
    plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 5,
             str(value), ha='center', va='bottom')

plt.show()

🔹 Grouped Bar Charts

Compare multiple data series side by side

import matplotlib.pyplot as plt
import numpy as np

# Sample data
categories = ['Q1', 'Q2', 'Q3', 'Q4']
sales_2022 = [100, 120, 140, 160]
sales_2023 = [110, 130, 150, 180]

# Set up positions for grouped bars
x = np.arange(len(categories))
width = 0.35  # Width of bars

# Create grouped bar chart
plt.figure(figsize=(10, 6))
bars1 = plt.bar(x - width/2, sales_2022, width, 
                label='2022', color='lightblue', alpha=0.8)
bars2 = plt.bar(x + width/2, sales_2023, width, 
                label='2023', color='orange', alpha=0.8)

plt.xlabel('Quarter')
plt.ylabel('Sales ($1000)')
plt.title('Quarterly Sales Comparison')
plt.xticks(x, categories)
plt.legend()
plt.grid(axis='y', alpha=0.3)

# Add value labels
for bars in [bars1, bars2]:
    for bar in bars:
        height = bar.get_height()
        plt.text(bar.get_x() + bar.get_width()/2., height + 2,
                f'{height}', ha='center', va='bottom')

plt.tight_layout()
plt.show()

# Three series comparison
categories = ['A', 'B', 'C', 'D']
series1 = [20, 35, 30, 35]
series2 = [25, 30, 35, 30]
series3 = [15, 25, 25, 40]

x = np.arange(len(categories))
width = 0.25

plt.figure(figsize=(10, 6))
plt.bar(x - width, series1, width, label='Series 1', alpha=0.8)
plt.bar(x, series2, width, label='Series 2', alpha=0.8)
plt.bar(x + width, series3, width, label='Series 3', alpha=0.8)

plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Three Series Comparison')
plt.xticks(x, categories)
plt.legend()
plt.show()

🔹 Stacked Bar Charts

Show parts of a whole using stacked bars

import matplotlib.pyplot as plt

# Sample data
categories = ['Team A', 'Team B', 'Team C', 'Team D']
wins = [12, 15, 10, 18]
losses = [8, 5, 10, 2]
draws = [5, 5, 5, 5]

# Create stacked bar chart
plt.figure(figsize=(10, 6))
plt.bar(categories, wins, label='Wins', color='green', alpha=0.8)
plt.bar(categories, losses, bottom=wins, label='Losses', color='red', alpha=0.8)

# Calculate bottom for draws (wins + losses)
bottom_draws = [w + l for w, l in zip(wins, losses)]
plt.bar(categories, draws, bottom=bottom_draws, label='Draws', color='yellow', alpha=0.8)

plt.xlabel('Teams')
plt.ylabel('Number of Games')
plt.title('Team Performance (Stacked)')
plt.legend()
plt.show()

# Percentage stacked bar chart
totals = [w + l + d for w, l, d in zip(wins, losses, draws)]
wins_pct = [w/t * 100 for w, t in zip(wins, totals)]
losses_pct = [l/t * 100 for l, t in zip(losses, totals)]
draws_pct = [d/t * 100 for d, t in zip(draws, totals)]

plt.figure(figsize=(10, 6))
plt.bar(categories, wins_pct, label='Wins %', color='green', alpha=0.8)
plt.bar(categories, losses_pct, bottom=wins_pct, label='Losses %', color='red', alpha=0.8)

bottom_draws_pct = [w + l for w, l in zip(wins_pct, losses_pct)]
plt.bar(categories, draws_pct, bottom=bottom_draws_pct, label='Draws %', color='yellow', alpha=0.8)

plt.xlabel('Teams')
plt.ylabel('Percentage')
plt.title('Team Performance (Percentage Stacked)')
plt.legend()
plt.ylim(0, 100)
plt.show()

🔹 Customized Bar Charts

Advanced styling and customization options

import matplotlib.pyplot as plt
import numpy as np

# Sample data
languages = ['Python', 'JavaScript', 'Java', 'C++', 'Go']
popularity = [85, 78, 72, 65, 58]

# Create custom styled bar chart
fig, ax = plt.subplots(figsize=(12, 8))

# Create gradient colors
colors = plt.cm.viridis(np.linspace(0, 1, len(languages)))

bars = ax.bar(languages, popularity, 
              color=colors,
              alpha=0.8,
              edgecolor='black',
              linewidth=1.5)

# Customize the plot
ax.set_xlabel('Programming Languages', fontsize=14, fontweight='bold')
ax.set_ylabel('Popularity Score', fontsize=14, fontweight='bold')
ax.set_title('Programming Language Popularity 2024', 
             fontsize=16, fontweight='bold', pad=20)

# Add grid
ax.grid(axis='y', alpha=0.3, linestyle='--')
ax.set_axisbelow(True)

# Add value labels on bars
for bar, value in zip(bars, popularity):
    height = bar.get_height()
    ax.text(bar.get_x() + bar.get_width()/2., height + 1,
            f'{value}%', ha='center', va='bottom', 
            fontsize=12, fontweight='bold')

# Customize appearance
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.set_ylim(0, 100)

plt.xticks(rotation=45, ha='right')
plt.tight_layout()
plt.show()

# Horizontal bar chart with custom styling
fig, ax = plt.subplots(figsize=(10, 8))

# Sort data for better visualization
sorted_data = sorted(zip(languages, popularity), key=lambda x: x[1])
sorted_languages, sorted_popularity = zip(*sorted_data)

bars = ax.barh(sorted_languages, sorted_popularity,
               color='steelblue', alpha=0.7,
               edgecolor='navy', linewidth=1)

# Add value labels
for bar, value in zip(bars, sorted_popularity):
    width = bar.get_width()
    ax.text(width + 1, bar.get_y() + bar.get_height()/2,
            f'{value}%', ha='left', va='center', fontweight='bold')

ax.set_xlabel('Popularity Score', fontsize=12, fontweight='bold')
ax.set_title('Programming Languages Ranked by Popularity', 
             fontsize=14, fontweight='bold')
ax.grid(axis='x', alpha=0.3)
ax.set_xlim(0, 100)

plt.tight_layout()
plt.show()

🧠 Test Your Knowledge

Which function creates horizontal bar charts?

What parameter is used to create stacked bars?