Advanced Code Example — Data Visualization#

This example creates a multi-panel business dashboard with four chart types (bar, line, scatter, horizontal bar), custom styling, annotations, and a cohesive visual design — all using Matplotlib and Pandas.


Business Scenario#

You are building a monthly customer analytics dashboard for retail leadership. The dashboard should show:

  1. Revenue by region (bar chart)
  2. Monthly revenue trend (line chart)
  3. Spend vs. purchase frequency relationship (scatter plot)
  4. Customer distribution by tier (horizontal bar chart)

Code#

import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import pandas as pd
import numpy as np

# ── Data ─────────────────────────────────────────────────────────────
regional_data = pd.DataFrame({
    'region':    ['Northwest', 'Southwest', 'Southeast', 'Northeast'],
    'revenue':   [48250.75, 36890.50, 22140.25, 41600.00],
    'customers': [85, 62, 41, 73]
})

monthly_data = pd.DataFrame({
    'month':   ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    'revenue': [28500, 31200, 29800, 35600, 38900, 42100,
                 44300, 43100, 46800, 51200, 58900, 63400]
})

customer_data = pd.DataFrame({
    'customer':        ['Alice J.', 'Bob M.', 'Carol C.', 'David K.',
                        'Eve T.', 'Frank L.', 'Grace P.', 'Helen S.'],
    'total_spent':     [1257, 430, 890, 125, 1450, 675, 980, 310],
    'purchase_count':  [12, 4, 9, 2, 15, 7, 11, 3],
    'tier':            ['Platinum', 'Silver', 'Gold', 'Standard',
                        'Platinum', 'Gold', 'Gold', 'Silver']
})

tier_counts = customer_data['tier'].value_counts()

# ── Gonzaga-inspired color palette ───────────────────────────────────
NAVY   = '#041E42'
RED    = '#C8102E'
SILVER = '#8B9BAA'
LIGHT  = '#E8EFF8'

# ── Figure Layout ─────────────────────────────────────────────────────
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
fig.suptitle('Customer Analytics Dashboard', fontsize=16, fontweight='bold', color=NAVY, y=0.98)
fig.patch.set_facecolor(LIGHT)

for ax in axes.flat:
    ax.set_facecolor('#ffffff')
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)

# ── Plot 1: Revenue by Region (bar) ───────────────────────────────────
ax1 = axes[0, 0]
bars = ax1.bar(regional_data['region'], regional_data['revenue'],
               color=[NAVY, RED, SILVER, NAVY], edgecolor='white', linewidth=0.8)
ax1.set_title('Revenue by Region', fontweight='bold', color=NAVY)
ax1.set_ylabel('Revenue ($)', color=NAVY)
ax1.tick_params(axis='x', rotation=10)
ax1.yaxis.set_major_formatter(mticker.FuncFormatter(lambda x, _: f'${x/1000:.0f}K'))

# Add value labels on bars
for bar in bars:
    h = bar.get_height()
    ax1.text(bar.get_x() + bar.get_width()/2, h + 300,
             f'${h/1000:.1f}K', ha='center', va='bottom', fontsize=9, color=NAVY)

# ── Plot 2: Monthly Revenue Trend (line) ─────────────────────────────
ax2 = axes[0, 1]
ax2.plot(monthly_data['month'], monthly_data['revenue'],
         color=RED, linewidth=2.5, marker='o', markersize=5, markerfacecolor=NAVY)
ax2.fill_between(range(len(monthly_data)), monthly_data['revenue'],
                 alpha=0.1, color=RED)
ax2.set_title('Monthly Revenue Trend', fontweight='bold', color=NAVY)
ax2.set_ylabel('Revenue ($)', color=NAVY)
ax2.tick_params(axis='x', rotation=20)
ax2.yaxis.set_major_formatter(mticker.FuncFormatter(lambda x, _: f'${x/1000:.0f}K'))
ax2.set_xticks(range(len(monthly_data)))
ax2.set_xticklabels(monthly_data['month'])

# Annotate peak month
peak_idx = monthly_data['revenue'].idxmax()
ax2.annotate(f"Peak: ${monthly_data['revenue'][peak_idx]/1000:.1f}K",
             xy=(peak_idx, monthly_data['revenue'][peak_idx]),
             xytext=(peak_idx - 2, monthly_data['revenue'][peak_idx] - 5000),
             arrowprops=dict(arrowstyle='->', color=RED),
             color=RED, fontsize=9)

# ── Plot 3: Spend vs. Frequency Scatter ──────────────────────────────
ax3 = axes[1, 0]
tier_colors = {'Platinum': NAVY, 'Gold': '#D4A017', 'Silver': SILVER, 'Standard': '#aaaaaa'}
colors = customer_data['tier'].map(tier_colors)

scatter = ax3.scatter(customer_data['purchase_count'], customer_data['total_spent'],
                      c=colors, s=120, edgecolors='white', linewidths=0.8, zorder=3)
ax3.set_title('Spend vs. Purchase Frequency', fontweight='bold', color=NAVY)
ax3.set_xlabel('Purchase Count', color=NAVY)
ax3.set_ylabel('Total Spent ($)', color=NAVY)

for _, row in customer_data.iterrows():
    ax3.annotate(row['customer'],
                 xy=(row['purchase_count'], row['total_spent']),
                 xytext=(4, 4), textcoords='offset points',
                 fontsize=7.5, color='#333333')

# Legend for tiers
from matplotlib.patches import Patch
legend_elements = [Patch(facecolor=c, label=t) for t, c in tier_colors.items()]
ax3.legend(handles=legend_elements, fontsize=8, title='Tier', title_fontsize=8)

# ── Plot 4: Tier Distribution (horizontal bar) ───────────────────────
ax4 = axes[1, 1]
tier_order = ['Platinum', 'Gold', 'Silver', 'Standard']
tier_vals = [tier_counts.get(t, 0) for t in tier_order]
bar_colors = [tier_colors[t] for t in tier_order]

hbars = ax4.barh(tier_order, tier_vals, color=bar_colors, edgecolor='white')
ax4.set_title('Customer Count by Tier', fontweight='bold', color=NAVY)
ax4.set_xlabel('Number of Customers', color=NAVY)
ax4.invert_yaxis()

for bar, val in zip(hbars, tier_vals):
    ax4.text(bar.get_width() + 0.05, bar.get_y() + bar.get_height()/2,
             f' {val}', va='center', fontsize=10, color=NAVY, fontweight='bold')

plt.tight_layout(rect=[0, 0, 1, 0.96])
plt.savefig('dashboard.png', dpi=150, bbox_inches='tight', facecolor=LIGHT)
plt.show()
print("Dashboard saved to dashboard.png")

Key Concepts Demonstrated#

ConceptWhere in Code
fig, axes = plt.subplots(2, 2)2×2 multi-panel figure layout
ax.bar() with color listCategorical bar with different bar colors
Value labels on barsax.text() positioned above each bar
ax.plot() with fillLine chart with shaded area
ax.annotate() with arrowCallout annotation on peak value
ax.scatter() with mapped colorsScatter colored by tier category
ax.barh()Horizontal bar chart
mticker.FuncFormatterCustom y-axis tick formatting
plt.savefig()Saving chart to file

Next: Jupyter Notebook →