Practical examples of data visualization with Matplotlib in Python
Real-world examples of data visualization with Matplotlib in Python
Let’s start where most tutorials don’t: with real examples of data visualization with Matplotlib in Python that mirror everyday analytics tasks. All code assumes you have:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
You can install the basics with:
pip install matplotlib numpy pandas
Time-series line chart: tracking trends over time
One of the best examples of data visualization with Matplotlib in Python is the classic time-series line chart. Think: daily active users, monthly revenue, or temperature trends.
## Example 1: Monthly revenue trend
months = pd.date_range("2023-01-01", periods=12, freq="M")
revenue = [12000, 13500, 14200, 16000, 15800, 17000,
18500, 19000, 21000, 22000, 23000, 25000]
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(months, revenue, marker="o", color="#1f77b4", linewidth=2)
ax.set_title("Monthly Revenue, 2023", fontsize=14, pad=12)
ax.set_ylabel("Revenue (USD)")
ax.set_xlabel("Month")
ax.grid(True, linestyle="--", alpha=0.3)
fig.autofmt_xdate()
## Highlight max point
max_idx = np.argmax(revenue)
ax.scatter(months[max_idx], revenue[max_idx], color="red", zorder=5)
ax.annotate("Peak", xy=(months[max_idx], revenue[max_idx]),
xytext=(10, 10), textcoords="offset points",
arrowprops=dict(arrowstyle="->", color="red"))
plt.tight_layout()
plt.show()
Why this works:
- The grid and markers make it easy to read values.
- The annotation calls out the key insight instead of forcing the reader to hunt for it.
- The x-axis uses real dates, which is how time data usually arrives in analytics pipelines.
If you’re working with real public time-series data — for example, health data from the U.S. Centers for Disease Control and Prevention — you can pull CSVs from https://data.cdc.gov and plug them straight into a pattern like this.
Categorical bar charts: comparing groups and categories
Another everyday example of data visualization with Matplotlib in Python is the bar chart: product comparisons, survey responses, or counts by category.
## Example 2: Average customer rating by product
products = ["A", "B", "C", "D"]
ratings = [4.3, 3.8, 4.7, 4.1]
fig, ax = plt.subplots(figsize=(6, 4))
bars = ax.bar(products, ratings, color=["#1f77b4", "#ff7f0e", "#2ca02c", "#9467bd"])
ax.set_title("Average Customer Rating by Product")
ax.set_ylabel("Rating (1–5)")
ax.set_ylim(0, 5)
## Label bars with exact values
for bar in bars:
height = bar.get_height()
ax.text(bar.get_x() + bar.get_width()/2, height + 0.05,
f"{height:.1f}", ha="center", va="bottom", fontsize=9)
plt.tight_layout()
plt.show()
Bar charts are one of the best examples because they’re easy to read and easy to customize. Real examples include:
- Comparing graduation rates across schools using data from https://nces.ed.gov
- Showing the share of patients by diagnosis category using data structures inspired by https://www.cdc.gov
Grouped and stacked bars: before-and-after or segment comparisons
Sometimes you need a more nuanced example of data visualization with Matplotlib in Python: comparing categories across multiple conditions, like before/after campaigns or segment breakdowns.
## Example 3: Grouped bar chart – website traffic by channel and device
channels = ["Organic", "Paid", "Social"]
mobile = [5200, 3100, 4400]
desktop = [4800, 3900, 2600]
x = np.arange(len(channels))
width = 0.35
fig, ax = plt.subplots(figsize=(7, 4))
ax.bar(x - width/2, mobile, width, label="Mobile", color="#1f77b4")
ax.bar(x + width/2, desktop, width, label="Desktop", color="#ff7f0e")
ax.set_xticks(x)
ax.set_xticklabels(channels)
ax.set_ylabel("Sessions")
ax.set_title("Website Sessions by Channel and Device")
ax.legend()
plt.tight_layout()
plt.show()
This is the kind of chart marketing teams actually use. You can adapt it to show outcomes from A/B tests, differences by region, or any other two-way breakdown.
Scatter plots: visualizing relationships and correlations
If you’re doing analytics or basic data science, one of the most important examples of data visualization with Matplotlib in Python is the scatter plot. It’s the workhorse for spotting relationships.
## Example 4: Advertising spend vs. sales
np.random.seed(42)
ad_spend = np.random.uniform(1000, 10000, 50)
noise = np.random.normal(0, 3000, 50)
sales = 2.5 * ad_spend + 20000 + noise
fig, ax = plt.subplots(figsize=(6, 4))
scatter = ax.scatter(ad_spend, sales, c=ad_spend, cmap="viridis", alpha=0.8)
ax.set_title("Advertising Spend vs. Sales")
ax.set_xlabel("Ad Spend (USD)")
ax.set_ylabel("Sales (USD)")
## Add trendline
m, b = np.polyfit(ad_spend, sales, 1)
ax.plot(ad_spend, m * ad_spend + b, color="red", linewidth=2, label="Trendline")
ax.legend()
cbar = fig.colorbar(scatter)
cbar.set_label("Ad Spend (USD)")
plt.tight_layout()
plt.show()
This example of a scatter plot does a few professional things:
- Uses color to encode a third dimension.
- Adds a trendline to make the relationship obvious.
- Labels axes with units so the chart is self-explanatory.
You can use this same pattern with real datasets from sources like https://data.gov, where you’ll see classic relationships such as income vs. education or pollution vs. health outcomes.
Histograms and KDE: understanding distributions
Another category where you want solid examples of data visualization with Matplotlib in Python is distribution analysis. You want to know if your data is skewed, heavy-tailed, or bimodal.
## Example 5: Distribution of delivery times
np.random.seed(0)
## Simulate delivery times (minutes)
fast = np.random.normal(25, 5, 800)
slow = np.random.normal(45, 7, 200)
delivery_times = np.concatenate([fast, slow])
fig, ax = plt.subplots(figsize=(7, 4))
ax.hist(delivery_times, bins=30, color="#1f77b4", alpha=0.7, edgecolor="white")
ax.set_title("Distribution of Delivery Times")
ax.set_xlabel("Minutes")
ax.set_ylabel("Number of Deliveries")
## Add vertical lines for mean and 95th percentile
mean_time = np.mean(delivery_times)
p95_time = np.percentile(delivery_times, 95)
ax.axvline(mean_time, color="red", linestyle="--", label=f"Mean: {mean_time:.1f} min")
ax.axvline(p95_time, color="orange", linestyle=":", label=f"95th %: {p95_time:.1f} min")
ax.legend()
plt.tight_layout()
plt.show()
Real examples include analyzing wait times in emergency departments (inspired by datasets you might see summarized at https://www.ahrq.gov) or test score distributions in education data from https://nces.ed.gov.
Box plots and violin plots: comparing distributions across groups
Histograms are great, but when you have multiple groups, box plots and violin plots are cleaner. This is a more advanced example of data visualization with Matplotlib in Python, but it pays off.
## Example 6: Test scores by teaching method
np.random.seed(1)
traditional = np.random.normal(75, 8, 100)
flipped = np.random.normal(80, 7, 100)
online = np.random.normal(72, 10, 100)
data = [traditional, flipped, online]
labels = ["Traditional", "Flipped", "Online"]
fig, ax = plt.subplots(figsize=(7, 4))
ax.boxplot(data, labels=labels, showmeans=True,
meanprops=dict(marker="o", markerfacecolor="red", markeredgecolor="black"))
ax.set_title("Exam Scores by Teaching Method")
ax.set_ylabel("Score (0–100)")
plt.tight_layout()
plt.show()
Education researchers, including those at universities like Harvard (https://www.gse.harvard.edu), often present results in this format because it quickly compares medians, ranges, and outliers.
Heatmaps: correlations and matrices at a glance
Heatmaps are one of the best examples of data visualization with Matplotlib in Python when you have matrix-shaped data: correlation matrices, confusion matrices, or pivot tables.
## Example 7: Correlation heatmap for numeric features
np.random.seed(42)
n = 300
age = np.random.randint(18, 70, n)
steps = np.random.normal(7000, 2000, n) + (age - 40) * -30
sleep = np.random.normal(7, 1, n) + (steps - 7000) / 4000
bmi = np.random.normal(27, 4, n) + (age - 40) / 10 - (steps - 7000) / 5000
health = pd.DataFrame({
"age": age,
"daily_steps": steps,
"sleep_hours": sleep,
"bmi": bmi
})
corr = health.corr(numeric_only=True)
fig, ax = plt.subplots(figsize=(6, 5))
im = ax.imshow(corr, cmap="coolwarm", vmin=-1, vmax=1)
ax.set_xticks(np.arange(len(corr.columns)))
ax.set_yticks(np.arange(len(corr.columns)))
ax.set_xticklabels(corr.columns, rotation=45, ha="right")
ax.set_yticklabels(corr.columns)
for i in range(len(corr.columns)):
for j in range(len(corr.columns)):
value = corr.iloc[i, j]
ax.text(j, i, f"{value:.2f}", ha="center", va="center",
color="black" if abs(value) < 0.5 else "white", fontsize=8)
fig.colorbar(im, ax=ax, label="Correlation")
ax.set_title("Correlation Matrix for Health Metrics")
plt.tight_layout()
plt.show()
This style of chart is common in health and epidemiology papers, including work you might see referenced by the National Institutes of Health at https://www.nih.gov.
Multi-panel dashboards: combining several plots in one figure
In real projects, you rarely send a single chart. You send a report. One of the most practical examples of data visualization with Matplotlib in Python is a multi-panel figure that tells a small story on one page.
## Example 8: Mini analytics dashboard
np.random.seed(123)
## Fake monthly metrics
months = pd.date_range("2024-01-01", periods=6, freq="M")
users = np.cumsum(np.random.randint(800, 1500, len(months)))
churn_rate = np.random.uniform(0.04, 0.09, len(months))
net_revenue = np.cumsum(np.random.randint(20000, 40000, len(months)))
fig, axes = plt.subplots(2, 2, figsize=(10, 6))
## Top-left: users over time
ax1 = axes[0, 0]
ax1.plot(months, users, marker="o", color="#1f77b4")
ax1.set_title("Active Users")
ax1.set_ylabel("Users")
fig.autofmt_xdate(rotation=30)
## Top-right: churn rate
ax2 = axes[0, 1]
ax2.bar(months, churn_rate * 100, color="#ff7f0e")
ax2.set_title("Monthly Churn Rate")
ax2.set_ylabel("Churn (%)")
## Bottom-left: net revenue
ax3 = axes[1, 0]
ax3.plot(months, net_revenue, marker="s", color="#2ca02c")
ax3.set_title("Cumulative Net Revenue")
ax3.set_ylabel("USD")
ax3.set_xlabel("Month")
## Bottom-right: blank or text summary
ax4 = axes[1, 1]
ax4.axis("off")
summary = (
f"Users grew from {users[0]:,} to {users[-1]:,} (+{(users[-1]/users[0]-1)*100:.1f}%).\n"
f"Average churn: {np.mean(churn_rate)*100:.1f}%.\n"
f"Net revenue reached ${net_revenue[-1]:,}."
)
ax4.text(0, 1, "Key Takeaways", fontsize=12, fontweight="bold", va="top")
ax4.text(0, 0.8, summary, fontsize=10, va="top")
fig.suptitle("Product Performance Snapshot – 2024 H1", fontsize=14)
plt.tight_layout(rect=[0, 0, 1, 0.95])
plt.show()
This is where examples of data visualization with Matplotlib in Python start to feel like a real analytics workflow. You can expand this pattern into a full reporting script that runs nightly and exports PNG or PDF summaries.
Styling tips that separate toy plots from production charts
You’ve seen several examples of data visualization with Matplotlib in Python. To make them presentation-ready, a few styling principles go a long way:
- Use figure sizes that match your medium. Wider for slide decks, taller for printed reports.
- Pick a consistent color palette. Avoid rainbow gradients; stick to 3–5 colors with meaning.
- Label everything clearly. Titles should answer “what am I looking at?”; axis labels should include units.
- Use annotations instead of legends when possible. They reduce eye travel.
- Avoid chart junk. Heavy grids, 3D effects, and random patterns distract from the data.
You can also use Matplotlib styles:
plt.style.use("ggplot") # or 'seaborn-v0_8', 'fivethirtyeight', etc.
This gives your examples of data visualization with Matplotlib in Python a more modern baseline look without much effort.
FAQ: common questions about Matplotlib visualization
Q: What are some simple examples of data visualization with Matplotlib in Python for beginners?
Line charts of stock prices, bar charts of category counts, and histograms of exam scores are great starting points. Each one is only a few lines of code and maps directly to the examples shown above.
Q: Can you give an example of combining Matplotlib with pandas for real data?
Yes. Load a CSV into a DataFrame, group or aggregate it, then pass the series directly to Matplotlib. For instance, df.groupby("month")["revenue"].sum().plot(kind="bar") will produce a bar chart using pandas’ Matplotlib integration.
Q: How do I choose the right chart type for my data?
Use line charts for trends over time, bar charts for category comparisons, scatter plots for relationships, histograms and box plots for distributions, and heatmaps for matrices or correlations. When in doubt, start simple and only add complexity if it clarifies the story.
Q: Are these examples of data visualization with Matplotlib in Python enough for production dashboards?
They’re a solid foundation. For full dashboards, you’ll often pair Matplotlib with tools like Flask, FastAPI, or Jupyter notebooks, or move to interactive libraries like Plotly. But the layout, styling, and annotation patterns here carry over directly.
Q: Where can I find real datasets to practice these visualization patterns?
Good starting points include https://data.gov for U.S. government data, https://data.cdc.gov for public health datasets, and education data from https://nces.ed.gov. Download a CSV, load it with pandas, and recreate the best examples from this guide with your own data.
Related Topics
Examples of Data Analysis with Pandas: 3 Practical Examples You’ll Actually Use
Practical examples of data visualization with Matplotlib in Python
Practical examples of examples of basic data types in Python
8 examples of working with dictionaries in Python – 3 practical examples you’ll use every day
Examples of Context Managers in Python: 3 Practical Patterns You’ll Actually Use
Examples of error handling in Python: practical examples for real projects
Explore More Python Code Snippets
Discover more examples and insights in this category.
View All Python Code Snippets