Visualize Data with Matplotlib
Learn matplotlib basics for data visualization in Python. Step-by-step tutorial covering core concepts, hands-on exercises, troubleshooting, and next steps for data science.
Focus: visualize data with matplotlib basics
You've cleaned your data, wrangled it into tidy DataFrames, and computed the key statistics — but when you present your findings to stakeholders, a wall of numbers gets a blank stare. Without visualization, patterns, outliers, and trends hide in plain sight, and your hard analysis loses its impact. This lesson teaches you the basics of visualizing data with Matplotlib, the foundational plotting library in Python, so you can turn raw data into compelling stories that drive decisions.
The problem this lesson solves
Numbers alone rarely communicate insight. A DataFrame with 10,000 rows of sales figures doesn't immediately reveal whether revenue is trending up or down, which product category has seasonal spikes, or where the outliers are. Humans are visual creatures — our brains process patterns in charts far faster than in tables. Without visualization, you risk:
- Missing hidden patterns — correlations, clusters, and anomalies that only show up visually
- Failing to persuade — stakeholders tune out when you show them dense spreadsheets
- Wasting debugging time — a quick plot can reveal data quality issues (e.g., negative values where impossible) that statistics miss
Matplotlib is the industry-standard plotting library in Python. It powers the visualizations in pandas, Seaborn, and countless data science pipelines. Learning its basics — pyplot, figure, axes, and the core plot types — unlocks the ability to explore data interactively and communicate results clearly.
By the end of this lesson, you'll be able to create line plots, scatter plots, bar charts, and histograms; customize labels and titles; and save your figures — the essential first step toward professional data storytelling.
Core concept / mental model
Think of Matplotlib like a digital canvas. You start with a blank canvas (a figure), you decide how many panels you want (subplots), and then you draw on each panel (an axes object). Each element — the title, axis labels, ticks — is a separate stroke you can control.
At its heart, Matplotlib's pyplot module provides a state-machine interface: you call plt.plot(x, y) and it draws on the "current" axes. But under the hood, everything lives in two core objects:
Figure— the entire window or image. It can contain multiple axes, titles, and a legend.Axes— the actual plotting area with x and y coordinates, ticks, and labels. This is what you draw on.
Pro tip: Most tutorials start with
plt.plot(...)without ever creating afigureoraxesexplicitly. That's fine for quick exploration, but once you want multiple subplots or fine control, you'll need to create them explicitly withplt.subplots().
This mental model — canvas → panels → strokes — will guide you through every plot you create, from a simple line chart to a complex multi-panel dashboard.
How it works step by step
-
Import the library — The standard import is
import matplotlib.pyplot as plt. This gives you thepyplotinterface that mimics MATLAB-style plotting. -
Prepare your data — Matplotlib works with Python lists, NumPy arrays, and pandas Series/DataFrames. Ensure your data is numeric and in the right shape (e.g., x and y of equal length).
-
Create a figure and axes — Use
fig, ax = plt.subplots()to get a figure and a single axes object. This is the cleanest way to start, as it gives you explicit control. -
Plot your data — Choose the right plot type:
ax.plot(x, y)for line plots,ax.scatter(x, y)for scatter plots,ax.bar(categories, values)for bar charts,ax.hist(data)for histograms. -
Customize — Add a title with
ax.set_title(), axis labels withax.set_xlabel()andax.set_ylabel(), and a legend withax.legend(). You can also change colors, markers, and line styles. -
Display or save — Use
plt.show()to display the plot in a script, orfig.savefig('plot.png')to save it to a file. In Jupyter notebooks,plt.show()renders inline.
Here's a minimal, complete example:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 1, 8, 7]
fig, ax = plt.subplots()
ax.plot(x, y, marker='o')
ax.set_title('Simple Line Plot')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
plt.show()
This creates a line chart with a title and axis labels. The marker='o' adds circles at each data point for readability.
Hands-on walkthrough
Let's put your understanding to work with a realistic scenario: monthly sales data for a retail store. We'll build a line plot, then add a scatter plot for a correlation check, and finish with a bar chart.
1. Line plot of sales trend
import matplotlib.pyplot as plt
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
sales = [12000, 15000, 13000, 18000, 16000, 22000]
fig, ax = plt.subplots()
ax.plot(months, sales, color='green', linewidth=2)
ax.set_title('Monthly Sales (H1)')
ax.set_xlabel('Month')
ax.set_ylabel('Sales ($)')
plt.show()
Output: A green line chart with 6 points, starting at 12000 and ending at 22000, with a clear upward trend — the visual instantly tells you sales are growing.
2. Scatter plot to explore a relationship
Save the figure to a file so you can reuse it in reports:
import matplotlib.pyplot as plt
ad_spend = [1000, 1500, 1200, 2000, 1800, 2500]
sales = [12000, 15000, 13000, 18000, 16000, 22000]
fig, ax = plt.subplots()
ax.scatter(ad_spend, sales, color='blue', alpha=0.5)
ax.set_title('Ad Spend vs. Sales')
ax.set_xlabel('Ad Spend ($)')
ax.set_ylabel('Sales ($)')
fig.savefig('ad_sales.png', dpi=150)
plt.show()
Output: A scatter plot showing a positive correlation — as ad spend increases, sales tend to rise. The alpha=0.5 makes points semi-transparent, useful for overlapping data.
3. Bar chart for categorical comparison
import matplotlib.pyplot as plt
categories = ['Electronics', 'Clothing', 'Food', 'Books']
gross_profit = [45000, 28000, 15000, 8000]
fig, ax = plt.subplots()
ax.bar(categories, gross_profit, color=['crimson', 'navy', 'gold', 'teal'])
ax.set_title('Gross Profit by Category')
ax.set_xlabel('Category')
ax.set_ylabel('Profit ($)')
plt.show()
Output: A bar chart with four bars, where Electronics is highest (45000) and Books is lowest (8000). The category comparison is immediate and avoids a table of numbers.
Pro tip: For histograms — to see data distribution — use
ax.hist(data, bins=20). Thebinsparameter controls the number of intervals, and tuning it can reveal different granularity of the distribution.
Compare options / when to choose what
Choosing the right plot type is critical to clear communication. Here's a quick comparison table:
| Plot Type | Best For | Example Use Case |
|---|---|---|
Line plot (ax.plot) |
Time series, trends | Monthly revenue over 12 months |
Scatter plot (ax.scatter) |
Relationships between two numeric variables | Correlation between marketing spend and sales |
Bar chart (ax.bar) |
Comparing categories | Average income by education level |
Histogram (ax.hist) |
Distribution of a single variable | Age distribution of customers |
Box plot (ax.boxplot) |
Summarizing distribution and outliers | Salary range by department |
Use a line plot when your x-axis is continuous and ordered (e.g., time). Use a scatter plot when you suspect a relationship and want to see its shape (linear, exponential, none). Reach for a bar chart when comparing discrete categories, and a histogram when you need to see the shape of a single variable's distribution.
Variations to consider:
- Instead of plt.subplots(), you can use plt.figure() and plt.plot() for quick one-off plots in a Jupyter notebook.
- For more advanced statistical plots, you can move to Seaborn, which is built on Matplotlib and provides higher-level interfaces for heatmaps, pair plots, and more.
- For a pure functional approach, try the MATLAB-style object-oriented interface, which is more explicit and recommended for complex figures.
Troubleshooting & edge cases
You'll hit common issues as you start plotting. Here's how to diagnose and fix them:
-
Plot doesn't show: In a script, forgetting
plt.show()results in nothing appearing. In Jupyter notebooks, ensure%matplotlib inline(or useplt.show()at the end). -
Missing x or y data: If you pass two arrays of different lengths to
ax.plot(x, y), Matplotlib raisesValueError: x and y must have same first dimension. Always checklen(x) == len(y). -
Non-numeric data causing error: If you pass strings where numbers are expected (e.g., in a scatter plot), you'll get a
TypeError. Convert withpd.to_numeric()orastype(float). -
All ticks overlapping: For many categories, the default tick labels may collide. Use
plt.xticks(rotation=45)to rotate labels and create space. -
Legend labels not showing: If you call
ax.legend()without adding labels to your plot, you'll see nothing. Passlabel='...'to each plot call, e.g.,ax.plot(x, y, label='Line 1'). -
Incorrect scale or missing outliers: If you expected a bar chart but got a jagged line, ensure you're using
ax.bar()notax.plot(). If your histogram looks flat, increasebinsto get finer detail.
Pro tip: Use
plt.figure(figsize=(10, 6))beforeplt.subplots()if you want to control the canvas size. For publications, setdpi=300when saving withsavefig. For exploratory work, lowerdpito keep files small.
What you learned & what's next
You've mastered the essentials of visualizing data with matplotlib basics: creating line plots, scatter plots, bar charts, and histograms; customizing with titles and labels; and saving figures. You can now choose the right plot type for your data and troubleshoot common errors — turning raw numbers into persuasive visuals.
You also connected the dots between visualization and the rest of your data pipeline: you can now take a tidy pandas DataFrame, quickly inspect its columns, and decide which visualization reveals the key insight.
What's next: In the next lesson, you'll learn how to customize matplotlib plots at a deeper level — controlling colors, styles, legends, subplots, and annotations — to create publication-ready charts that tell a clearer story. You'll also explore how to integrate matplotlib with pandas for rapid exploratory data analysis.
To practice what you've learned, try plotting your own dataset: load a CSV with pandas, pick a numeric column, and create a histogram. Experiment with different bins values and see how the shape changes. Then, save the figure and share it — you're now a data storyteller.
Practice recap
Mini exercise: Load a small dataset (e.g., a CSV of daily temperatures) into pandas, then create a line plot of temperature over time. Add a title and axis labels, then save the figure as a PNG. Experiment with linewidth and color parameters to improve readability. Finally, create a histogram of temperature values with 20 bins and compare the shapes.
Common mistakes
- Forgetting
plt.show()in a script — the plot never appears. In Jupyter, use%matplotlib inlineor end withplt.show(). - Passing x and y arrays of different lengths to
plt.plot()— raises a ValueError. Always checklen(x) == len(y). - Calling
ax.legend()without specifyinglabelin the plot call — the legend is empty. - Using a line plot for categorical data — use
ax.bar()instead to avoid misleading trends.
Variations
- Use
plt.plot()andplt.figure()directly for quick one-off plots in a notebook, instead of the explicitfig, ax = plt.subplots()pattern. - Adopt the object-oriented interface (
fig, ax = plt.subplots()) for complex figures with multiple subplots — recommended for production code. - Layer on Seaborn (built on Matplotlib) for high-level statistical plots like heatmaps and pair plots.
Real-world use cases
- A financial analyst plots daily stock prices to spot trends and anomalies before deciding to buy or sell.
- A marketing team creates a scatter plot of ad spend vs. conversions to justify the next campaign budget.
- An operations manager uses a histogram of delivery times to identify bottlenecks and set service-level targets.
Key takeaways
- Matplotlib's core objects are
Figure(the canvas) andAxes(the plotting area) — useplt.subplots()to get both explicitly. - Choose the right plot type: line for trends, scatter for relationships, bar for categorical comparisons, histogram for distributions.
- Always label your axes and add a title — context is as important as the data itself.
- Save your figures with
fig.savefig()with appropriatedpifor reports or publications. - Troubleshoot common errors by checking data type, array lengths, and calling order of
plt.show(). - Matplotlib is the foundation for other visualization libraries like Seaborn — mastering it pays off.
Keep learning
Related tutorials, quizzes, and articles for this topic.
Discussion
Questions, corrections, and tips help everyone reading this page.
0 comments
Add a comment
No comments yet — start the thread.