Create a Dashboard-Style Layout
Description:
This code demonstrates how to create a dashboard-like view by organizing multiple plots (metrics) in a grid layout using matplotlib
's plt.subplot()
or plt.subplots()
.
Code Explanation:
-
We divide the screen into 2 rows and 2 columns (
2x2 grid
) to create a dashboard. -
Each subplot shows a different metric (Sales, Revenue, Units, and a summary Pie chart).
-
fig.suptitle()
adds a big title on top of all subplots. -
plt.tight_layout()
ensures that labels and titles don’t overlap.
Program:
import matplotlib.pyplot as plt
import pandas as pd
# Sample data
data = {
'Date': pd.date_range(start='2024-01-01', periods=7, freq='D'),
'Sales': [100, 120, 90, 140, 160, 130, 150],
'Revenue': [1000, 1500, 1200, 1800, 2000, 1700, 1900],
'Units': [10, 12, 9, 14, 16, 13, 15]
}
df = pd.DataFrame(data)
# Create a 2x2 dashboard layout
fig, axs = plt.subplots(2, 2, figsize=(12, 8))
# Plot each metric in a different subplot
axs[0, 0].plot(df['Date'], df['Sales'], marker='o', color='blue')
axs[0, 0].set_title('Daily Sales')
axs[0, 1].bar(df['Date'], df['Revenue'], color='green')
axs[0, 1].set_title('Revenue')
axs[1, 0].plot(df['Date'], df['Units'], color='red', linestyle='--', marker='^')
axs[1, 0].set_title('Units Sold')
axs[1, 1].pie([sum(df['Sales']), sum(df['Revenue']), sum(df['Units'])],
labels=['Sales', 'Revenue', 'Units'], autopct='%1.1f%%', startangle=90)
axs[1, 1].set_title('Metric Distribution')
# Rotate x labels for clarity
for ax in axs.flat:
if ax in [axs[0, 0], axs[0, 1], axs[1, 0]]:
ax.tick_params(axis='x', labelrotation=45)
# Set main title
fig.suptitle('Business Metrics Dashboard', fontsize=16)
# Adjust layout
plt.tight_layout(rect=[0, 0, 1, 0.95]) # Leave space for suptitle
plt.show()
Output: