Lesson 68 of 70 – Python Matplotlib
97%

Python Matplotlib

Matplotlib is a popular Python library used to create charts, graphs and other visualizations. It is widely used in data analysis, scientific computing and data science.

Note: Matplotlib can create line charts, bar charts, pie charts, scatter plots, histograms and many other types of visualizations.
What is Matplotlib?

Matplotlib is a Python visualization library that provides tools for creating static, animated and interactive visualizations.

It is commonly used together with libraries such as NumPy and Pandas.

  • Line charts
  • Bar charts
  • Pie charts
  • Scatter plots
  • Histograms
  • Box plots
  • Data visualization
Installing Matplotlib

Matplotlib can be installed using pip.

pip install matplotlib

You can also use:

python -m pip install matplotlib
Importing Matplotlib

The pyplot module is commonly imported using the alias plt.

import matplotlib.pyplot as plt
First Line Chart

The plot() function can be used to create a line chart.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

y = [10, 20, 15, 30, 25]

plt.plot(x, y)

plt.show()

The show() function displays the chart.

Adding a Title

The title() function adds a title to the chart.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]

y = [10, 20, 15, 25]

plt.plot(x, y)

plt.title("Student Performance")

plt.show()
Adding X and Y Labels

Use xlabel() and ylabel() to label the axes.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]

y = [10, 20, 15, 25]

plt.plot(x, y)

plt.xlabel("Month")

plt.ylabel("Sales")

plt.title("Monthly Sales")

plt.show()
Adding Grid

The grid() function displays grid lines on the chart.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]

y = [10, 20, 15, 25]

plt.plot(x, y)

plt.grid()

plt.show()
Line Style

The linestyle argument can be used to change the line style.

plt.plot(
    x,
    y,
    linestyle="--"
)

plt.show()

Common styles include:

  • - Solid line
  • -- Dashed line
  • : Dotted line
  • -. Dash-dot line
Markers

Markers can be used to highlight individual data points.

plt.plot(
    x,
    y,
    marker="o"
)

plt.show()

Common marker examples include o, s, ^ and *.

Line Chart with Marker
import matplotlib.pyplot as plt

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

sales = [
    100,
    150,
    120,
    180
]

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

plt.title("Monthly Sales")

plt.xlabel("Month")

plt.ylabel("Sales")

plt.grid()

plt.show()
Multiple Lines

Multiple datasets can be plotted on the same axes.

import matplotlib.pyplot as plt

months = [1, 2, 3, 4]

python_students = [20, 30, 35, 40]

java_students = [15, 25, 30, 35]

plt.plot(
    months,
    python_students,
    label="Python"
)

plt.plot(
    months,
    java_students,
    label="Java"
)

plt.legend()

plt.show()
Legend

The legend() function displays labels for plotted datasets.

plt.plot(
    [1, 2, 3],
    [10, 20, 30],
    label="Sales"
)

plt.legend()

plt.show()
Bar Chart

The bar() function creates a vertical bar chart.

import matplotlib.pyplot as plt

courses = [
    "Python",
    "Java",
    "SQL"
]

students = [
    50,
    40,
    30
]

plt.bar(
    courses,
    students
)

plt.title("Students by Course")

plt.xlabel("Course")

plt.ylabel("Students")

plt.show()
Horizontal Bar Chart

The barh() function creates a horizontal bar chart.

courses = [
    "Python",
    "Java",
    "SQL"
]

students = [
    50,
    40,
    30
]

plt.barh(
    courses,
    students
)

plt.show()
Scatter Plot

The scatter() function creates a scatter plot.

import matplotlib.pyplot as plt

hours = [
    1, 2, 3, 4, 5
]

marks = [
    40, 50, 60, 75, 85
]

plt.scatter(
    hours,
    marks
)

plt.xlabel("Study Hours")

plt.ylabel("Marks")

plt.title("Study Hours vs Marks")

plt.show()
Pie Chart

The pie() function creates a pie chart.

import matplotlib.pyplot as plt

courses = [
    "Python",
    "Java",
    "SQL"
]

students = [
    50,
    30,
    20
]

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

plt.title("Course Distribution")

plt.show()
Histogram

A histogram shows the distribution of numerical data.

import matplotlib.pyplot as plt

marks = [
    45, 50, 55, 60,
    62, 65, 70, 72,
    75, 80, 85, 90
]

plt.hist(marks)

plt.xlabel("Marks")

plt.ylabel("Frequency")

plt.title("Marks Distribution")

plt.show()
Subplots

Subplots allow multiple charts to be placed within one figure.

import matplotlib.pyplot as plt

plt.subplot(1, 2, 1)

plt.plot(
    [1, 2, 3],
    [10, 20, 30]
)

plt.title("Line Chart")

plt.subplot(1, 2, 2)

plt.bar(
    [1, 2, 3],
    [30, 20, 10]
)

plt.title("Bar Chart")

plt.show()

Here, 1, 2, 1 means one row, two columns and the first plot.

Figure and Axes

For more structured visualizations, Matplotlib provides the subplots() function.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.plot(
    [1, 2, 3],
    [10, 20, 30]
)

ax.set_title("Sales")

ax.set_xlabel("Month")

ax.set_ylabel("Amount")

plt.show()
Changing Figure Size

The figsize argument controls the figure dimensions.

import matplotlib.pyplot as plt

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

plt.plot(
    [1, 2, 3],
    [10, 20, 30]
)

plt.show()
Saving a Chart

The savefig() function saves a figure to a file.

import matplotlib.pyplot as plt

plt.plot(
    [1, 2, 3],
    [10, 20, 30]
)

plt.title("Sales")

plt.savefig(
    "sales.png"
)

plt.show()

The file format can be inferred from the filename extension.

Using NumPy with Matplotlib

Matplotlib works well with NumPy arrays.

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(
    0,
    10,
    0.1
)

y = np.sin(x)

plt.plot(x, y)

plt.title("Sine Wave")

plt.show()
Using Pandas with Matplotlib

Pandas DataFrames and Series can also be plotted using their plotting methods, which commonly use Matplotlib as the visualization backend.

import pandas as pd
import matplotlib.pyplot as plt

data = {
    "Month": [
        "Jan",
        "Feb",
        "Mar"
    ],
    "Sales": [
        100,
        150,
        130
    ]
}

df = pd.DataFrame(data)

df.plot(
    x="Month",
    y="Sales"
)

plt.title("Monthly Sales")

plt.show()
Customizing Ticks

Functions such as xticks() and yticks() can be used to control tick positions and labels.

import matplotlib.pyplot as plt

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

sales = [
    100,
    150,
    120,
    180
]

plt.plot(
    months,
    sales
)

plt.xticks(
    rotation=45
)

plt.show()
Adding Text to a Chart

The text() function can add text at a specified position.

import matplotlib.pyplot as plt

x = [1, 2, 3]

y = [10, 20, 30]

plt.plot(x, y)

plt.text(
    2,
    20,
    "Important Point"
)

plt.show()
Box Plot

A box plot is useful for displaying the distribution of numerical data and identifying potential outliers.

import matplotlib.pyplot as plt

marks = [
    45, 50, 55, 60,
    62, 65, 70, 72,
    75, 80, 85, 90
]

plt.boxplot(marks)

plt.title("Marks Distribution")

plt.show()
Changing Chart Limits

The xlim() and ylim() functions can control the visible range of the axes.

import matplotlib.pyplot as plt

plt.plot(
    [1, 2, 3, 4],
    [10, 20, 30, 40]
)

plt.xlim(1, 4)

plt.ylim(0, 50)

plt.show()
Tight Layout

The tight_layout() function can automatically adjust spacing between plot elements.

import matplotlib.pyplot as plt

plt.plot(
    [1, 2, 3],
    [10, 20, 30]
)

plt.title("Sales")

plt.xlabel("Month")

plt.ylabel("Amount")

plt.tight_layout()

plt.show()
Common Matplotlib Mistakes
  • Forgetting to install Matplotlib.
  • Forgetting to import pyplot.
  • Forgetting to call plt.show() when a display is needed.
  • Providing x and y data with incompatible lengths.
  • Using an inappropriate chart type for the data.
  • Forgetting chart titles and axis labels.
  • Overloading a chart with too much information.
  • Forgetting to save the figure before closing or clearing it when a file output is required.
Complete Matplotlib Example
import matplotlib.pyplot as plt

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

sales = [
    100,
    150,
    130,
    180,
    200
]

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

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

plt.title("Monthly Sales")

plt.xlabel("Month")

plt.ylabel("Sales")

plt.grid()

plt.legend()

plt.tight_layout()

plt.show()
Key Points
  • Matplotlib is a Python library for data visualization.
  • matplotlib.pyplot is commonly imported as plt.
  • plot() creates line charts.
  • bar() creates vertical bar charts.
  • barh() creates horizontal bar charts.
  • scatter() creates scatter plots.
  • pie() creates pie charts.
  • hist() creates histograms.
  • boxplot() creates box plots.
  • title() adds a chart title.
  • xlabel() and ylabel() label the axes.
  • legend() displays labels for plotted datasets.
  • grid() displays grid lines.
  • savefig() saves a chart to a file.
  • subplots() creates figure and axes objects.
  • Matplotlib works well with NumPy and Pandas.
  • Charts help make numerical and categorical data easier to understand.

🧠 Quick Quiz

Question: Which Matplotlib function is commonly used to create a line chart?