Lesson 67 · Data Visualization

Python Matplotlib

Learn how to transform Python data into meaningful visualizations using Matplotlib — one of the most important libraries for data analysis, data science, and reporting.

50–60 minutes Intermediate Data Visualization
0%
01

Learning Objectives

By the end of this lesson, you will be able to create professional charts from Python data using Matplotlib.

You will learn how to:

  • Install and import Matplotlib.
  • Create line, bar, pie, histogram, and scatter charts.
  • Customize titles, labels, legends, markers, and grids.
  • Understand the difference between figures and axes.
  • Create multiple charts using subplots.
  • Add annotations and control chart limits.
  • Save visualizations as image files.
  • Select the right chart for a particular analytical question.
02

What Is Matplotlib?

Matplotlib is a Python library used to create static, animated, and interactive visualizations.

It is especially useful when working with numerical data, statistics, scientific computing, and data analysis.

Matplotlib works particularly well with libraries such as NumPy and Pandas.

Think of Matplotlib as a communication tool

A table may contain thousands of numbers, but a well-designed chart can reveal a trend or comparison almost instantly.

import matplotlib.pyplot as plt

The pyplot module provides many convenient functions for creating charts.

03

Why Data Visualization Matters

Data visualization converts raw numbers into visual patterns. This makes it easier to understand trends, comparisons, distributions, and relationships.

Example

Suppose monthly sales are:

sales = [1200, 1500, 1100, 1800, 2100]

Looking at the numbers tells you the values. A line chart, however, immediately shows how sales changed over time.

Visualization can help answer questions such as:

  • Are sales increasing?
  • Which product sells the most?
  • How are values distributed?
  • Is advertising associated with higher sales?
  • Which month performed best?
04

Installing Matplotlib

If Matplotlib is not already installed, install it using pip.

python -m pip install matplotlib

If you are working inside a virtual environment, make sure the environment is activated before installing the package.

Important

If Python cannot find Matplotlib after installation, check that you installed it into the same Python environment that your program is using.

05

Importing Matplotlib

The most common way to import Matplotlib's plotting functionality is:

import matplotlib.pyplot as plt

The name plt is the conventional alias used in Python programs.

Why use an alias?

Instead of writing the longer module name repeatedly, you can write concise expressions such as plt.plot() and plt.show().

06

Creating Your First Line Plot

A line chart is excellent for showing how a value changes across an ordered sequence, such as time.

import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May"]
sales = [1200, 1500, 1100, 1800, 2100]

plt.plot(months, sales)

plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")

plt.show()
What the chart communicates

The horizontal axis represents the months and the vertical axis represents sales.

The connected points show the movement of sales from one month to another.

Best use

Use line charts primarily for trends and ordered data. Time-series data is one of their most common applications.

07

Understanding Figure & Axes

Matplotlib has an object-oriented interface built around Figure and Axes.

  • Figure: the overall canvas or window.
  • Axes: the actual plotting area.
import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May"]
sales = [1200, 1500, 1100, 1800, 2100]

fig, ax = plt.subplots()

ax.plot(months, sales)

ax.set_title("Monthly Sales")
ax.set_xlabel("Month")
ax.set_ylabel("Revenue")

plt.show()

Why learn this approach?

The object-oriented approach becomes especially useful when you create multiple charts, subplots, reusable functions, or more complex visualizations.

08

Plotting Multiple Lines

You can compare multiple datasets on the same chart.

import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May"]

online = [1200, 1500, 1300, 1800, 2100]
store = [1000, 1100, 1250, 1400, 1600]

plt.plot(months, online, label="Online")
plt.plot(months, store, label="Store")

plt.title("Online vs Store Sales")
plt.xlabel("Month")
plt.ylabel("Sales")

plt.legend()

plt.show()

The label values identify each line and plt.legend() displays those labels.

Avoid excessive lines

A chart containing too many lines can become difficult to read. If many categories must be compared, consider whether separate charts or another visualization would communicate the information better.

09

Titles, Labels & Legends

A chart should explain itself. Titles, axis labels, and legends provide essential context.

plt.title("Monthly Revenue")
plt.xlabel("Month")
plt.ylabel("Revenue")

plt.legend()

Without labels, viewers may not know what the numbers represent.

Professional rule

Write meaningful labels. Instead of Value, use something specific such as Revenue ($) or Units Sold.

10

Line Styles and Markers

Matplotlib allows you to change how data points and lines are displayed.

plt.plot(
    months,
    sales,
    marker="o",
    linestyle="--"
)

plt.show()

Common marker examples include:

  • "o" — circle
  • "s" — square
  • "^" — triangle
  • "x" — x marker

Common line styles include:

  • "-" — solid
  • "--" — dashed
  • ":" — dotted

Use styling with purpose

Styling should improve readability, not simply decorate the chart.

11

Bar Charts

Bar charts are excellent for comparing separate categories.

import matplotlib.pyplot as plt

products = ["Laptop", "Phone", "Tablet", "Monitor"]
sales = [120, 180, 100, 75]

plt.bar(products, sales)

plt.title("Product Sales")
plt.xlabel("Product")
plt.ylabel("Units Sold")

plt.show()

Typical use cases

  • Product sales comparison
  • Sales by department
  • Orders by category
  • Employees by team
  • Revenue by region
12

Horizontal Bar Charts

A horizontal bar chart uses barh().

products = ["Laptop", "Phone", "Tablet", "Monitor"]
sales = [120, 180, 100, 75]

plt.barh(products, sales)

plt.title("Product Sales")

plt.show()

Horizontal bars are particularly useful when category names are long.

13

Grouped Bar Charts

Grouped bars allow you to compare multiple measurements for the same categories.

import numpy as np
import matplotlib.pyplot as plt

products = ["Laptop", "Phone", "Tablet", "Monitor"]

x = np.arange(len(products))
width = 0.35

online = [120, 180, 100, 75]
store = [90, 150, 120, 60]

fig, ax = plt.subplots()

ax.bar(x - width / 2, online, width, label="Online")
ax.bar(x + width / 2, store, width, label="Store")

ax.set_xticks(x)
ax.set_xticklabels(products)

ax.set_ylabel("Units Sold")
ax.set_title("Online vs Store Sales")

ax.legend()

plt.show()

Analytical question

A grouped bar chart is useful when you want to compare two or more measurements within the same categories.

14

Pie Charts

Pie charts show how categories contribute to a whole.

import matplotlib.pyplot as plt

labels = ["Electronics", "Clothing", "Home", "Books"]
values = [40, 25, 20, 15]

plt.pie(
    values,
    labels=labels,
    autopct="%1.1f%%"
)

plt.title("Sales Distribution")

plt.show()

Use pie charts carefully

Pie charts become difficult to read when there are many categories or when values are very similar. A bar chart may be clearer in those situations.

15

Histograms

A histogram shows the distribution of numerical values by grouping them into intervals called bins.

import matplotlib.pyplot as plt

ages = [21, 22, 25, 25, 27, 29, 31, 32, 35, 36, 40, 42]

plt.hist(
    ages,
    bins=5
)

plt.title("Age Distribution")
plt.xlabel("Age")
plt.ylabel("Frequency")

plt.show()

Histograms help answer questions such as:

  • Where are most observations concentrated?
  • Is the distribution spread out?
  • Are there unusually high or low values?
  • Does the data appear symmetric or skewed?
16

Scatter Plots

Scatter plots are used to examine the relationship between two numerical variables.

import matplotlib.pyplot as plt

advertising = [100, 150, 200, 250, 300]
sales = [1200, 1500, 1800, 2200, 2600]

plt.scatter(
    advertising,
    sales
)

plt.xlabel("Advertising Spend")
plt.ylabel("Sales")
plt.title("Advertising vs Sales")

plt.show()

Think in relationships

A scatter plot can help you visually investigate whether two numerical variables appear to move together.

Remember that visual correlation does not automatically prove that one variable causes another.

17

Creating Subplots

Subplots allow multiple charts to be placed inside one figure.

import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May"]
sales = [1200, 1500, 1100, 1800, 2100]

products = ["Laptop", "Phone", "Tablet", "Monitor"]
product_sales = [120, 180, 100, 75]

fig, axes = plt.subplots(
    1,
    2,
    figsize=(12, 4)
)

axes[0].plot(months, sales)
axes[0].set_title("Monthly Sales")

axes[1].bar(products, product_sales)
axes[1].set_title("Product Sales")

plt.tight_layout()
plt.show()

Here, axes[0] represents the first plotting area and axes[1] represents the second.

18

Grid, Ticks & Limits

Grid lines can make numerical comparisons easier.

plt.plot(months, sales)

plt.ylim(0, 2500)
plt.grid(True)

plt.show()

You can also control the x-axis range with xlim().

plt.xlim(0, 4)
plt.ylim(0, 2500)

Avoid misleading axes

Axis limits can dramatically change the visual impression of a chart. Always choose them carefully and honestly.

19

Adding Annotations

Annotations allow you to point out important observations directly on a chart.

import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May"]
sales = [1200, 1500, 1100, 1800, 2100]

best_month = sales.index(max(sales))

plt.plot(months, sales, marker="o")

plt.annotate(
    "Highest Sales",
    xy=(best_month, sales[best_month]),
    xytext=(best_month, sales[best_month] + 300),
    arrowprops={"arrowstyle": "->"}
)

plt.show()

Annotations are useful for highlighting:

  • Best-performing month
  • Unexpected drop
  • Peak sales
  • Important business event
  • Outlier
20

Figure Size & Layout

You can control the size of a figure using figsize.

import matplotlib.pyplot as plt

plt.figure(figsize=(10, 5))

plt.plot(months, sales)

plt.title("Monthly Sales")

plt.show()

For multiple charts, tight_layout() helps prevent labels and titles from overlapping.

plt.tight_layout()

Professional visualization

A chart that is technically correct can still be difficult to use if labels overlap or text is too small. Layout is part of data communication.

21

Saving Charts

Charts can be saved as image files instead of displaying them only on screen.

plt.savefig(
    "monthly_sales.png",
    dpi=300,
    bbox_inches="tight"
)

The resulting image can be used in:

  • Reports
  • Presentations
  • Business dashboards
  • Documents
  • Data analysis portfolios

What do the options mean?

  • dpi=300 requests high-resolution output.
  • bbox_inches="tight" helps reduce unnecessary whitespace.
22

Practical Data Science Example

Imagine you are a data analyst working with an ecommerce company. Management wants to understand monthly revenue.

import matplotlib.pyplot as plt

months = [
    "Jan", "Feb", "Mar", "Apr",
    "May", "Jun", "Jul", "Aug",
    "Sep", "Oct", "Nov", "Dec"
]

revenue = [
    12000, 14500, 13800, 16000,
    17200, 18100, 17500, 19000,
    21000, 22500, 21800, 25000
]

plt.figure(figsize=(11, 5))

plt.plot(
    months,
    revenue,
    marker="o"
)

plt.title("Monthly Ecommerce Revenue")
plt.xlabel("Month")
plt.ylabel("Revenue")

plt.grid(True)

plt.tight_layout()
plt.show()

This visualization allows management to quickly identify the overall revenue trend and stronger-performing months.

Data analyst mindset

Do not start by asking, "Which chart looks impressive?" Start by asking, "What business question am I trying to answer?"

Choosing the Right Chart

  • Line chart: trends over an ordered sequence.
  • Bar chart: comparison between categories.
  • Pie chart: simple part-to-whole relationships.
  • Histogram: distribution of numerical data.
  • Scatter plot: relationship between two numerical variables.
23

Common Matplotlib Mistakes

Mistake 1 — Forgetting plt.show()

In many environments, especially scripts, you need plt.show() to display the chart.

Mistake 2 — Incorrect labels

A chart without meaningful labels can be difficult to interpret.

Mistake 3 — Misleading axes

Changing axis limits can exaggerate or hide differences. Always make sure the visualization represents the data honestly.

Mistake 4 — Too much information

Too many lines, categories, labels, or annotations can make a chart harder to understand.

Mistake 5 — Choosing the wrong chart

A chart can be beautifully formatted and still be the wrong visualization for the question.

Mistake 6 — Forgetting tight_layout()

When working with multiple charts, labels and titles can overlap. plt.tight_layout() often helps.

Mistake 7 — Confusing pyplot and Axes

plt.plot() is convenient for simple charts, while the object-oriented fig, ax approach provides better control for complex visualizations.

24

Practice Exercises

Exercise 1 — Monthly Sales

Create a line chart using five months and their sales values. Add a title and axis labels.

Exercise 2 — Product Comparison

Create a bar chart showing sales for five products.

Exercise 3 — Customer Ages

Create a histogram using a list of customer ages. Experiment with different numbers of bins.

Exercise 4 — Marketing Relationship

Create a scatter plot comparing advertising spending against sales.

Exercise 5 — Multiple Charts

Create two charts inside the same figure using plt.subplots().

25

Mini Challenge — Sales Dashboard Charts

You are working as a junior data analyst for an ecommerce company. Create a small visualization report using Matplotlib.

Your Tasks

  1. Create monthly sales data for 12 months.
  2. Create a line chart showing the monthly sales trend.
  3. Create a bar chart comparing sales for at least four products.
  4. Create a pie chart showing category sales distribution.
  5. Create a scatter plot comparing advertising spend against revenue.
  6. Place two charts inside a subplot figure.
  7. Add appropriate titles and axis labels.
  8. Use a legend where it improves understanding.
  9. Add a grid where appropriate.
  10. Save at least one chart as a PNG file.

Suggested Starting Data

months = [
    "Jan", "Feb", "Mar", "Apr",
    "May", "Jun", "Jul", "Aug",
    "Sep", "Oct", "Nov", "Dec"
]

monthly_sales = [
    1200, 1500, 1350, 1700,
    1850, 2100, 1950, 2200,
    2400, 2600, 2500, 2900
]

products = [
    "Laptop",
    "Phone",
    "Tablet",
    "Monitor"
]

product_sales = [
    120,
    180,
    100,
    75
]

advertising = [
    100, 150, 200, 250, 300
]

revenue = [
    1200, 1500, 1800, 2200, 2600
]

Challenge goal

Do not focus only on making the charts work. Try to make them understandable to someone who has never seen your code.

26

Knowledge Check

Test your understanding before moving to the next lesson.

1. What is Matplotlib primarily used for?

2. Which module is commonly imported as plt?

3. Which function creates a basic line plot?

4. What is the difference between Figure and Axes?

5. Which function displays a legend?

6. Which chart is generally useful for comparing categories?

7. Which chart is designed to show a numerical distribution?

8. Which chart is useful for examining a relationship between two numerical variables?

9. What does plt.savefig() do?

10. What should primarily determine your chart choice?

27

Lesson Summary

Matplotlib is one of the most important visualization libraries in the Python ecosystem.

What you should now know

  • Matplotlib creates visualizations from Python data.
  • matplotlib.pyplot is commonly imported as plt.
  • plt.plot() creates line charts.
  • Bar charts compare categories.
  • Pie charts show simple part-to-whole relationships.
  • Histograms show numerical distributions.
  • Scatter plots show relationships between numerical variables.
  • Figures and Axes provide a powerful object-oriented approach.
  • Subplots allow multiple charts in one figure.
  • Titles, labels, legends, grids, and annotations improve communication.
  • savefig() saves charts for reports and presentations.
  • The best chart is determined by the analytical question.

In the next lesson, you will move from visualization into Python Data Analysis, where you will combine data structures, Pandas, NumPy, cleaning techniques, and visualizations to answer practical questions from datasets.

Ready for the next lesson?

Mark this lesson complete when you are comfortable creating and interpreting basic Matplotlib visualizations.