Master Matplotlib From Scratch

Learn Matplotlib fundamentals, figure anatomy, basic plotting, chart customization, subplots, statistical visualizations, color mapping, annotations, 3D plotting, animations, and interactive visualizations through structured practical lessons.

COURSE SYLLABUS
1. Introduction & Environment Setup
What is Matplotlib? Installation Environment Setup Imports and Conventions
2. Core Figure Anatomy & Structures
Figure vs Axes Creating Canvas Dimensions and Resolution Saving Visuals
3. Basic Plotting
Line Plots Scatter Plots Bar Charts Histograms
4. Basic Visual Formatting & Labels
Titles and Labels Text Customization Legends Grid Lines
5. Advanced Plot Customization
Format Strings Line and Marker Styling Color Systems Transparency
6. Axis Control, Ticks & Limits
Axis Limits Custom Ticks Tick Labels Axis Scaling
7. Multi-Plot Layouts & Subplots
Basic Subplots Indexing Subplots Layout Tuning Advanced Grids
8. Advanced Statistical & Data-Specific Plots
Pie Charts Box and Whisker Plots Violin Plots Error Bars
9. Color Mapping & 2D Data Visualizations
Colormaps Heatmaps and Images Colorbars Contour Plots
10. Annotations & Shapes
Basic Text Smart Annotations Drawing Shapes Shading Areas
11. Customizing Styles & Themes
Built-in Styles Custom Style Sheets Global Configurations
12. Object-Oriented API vs Pyplot
Pyplot vs Object-Oriented API Transitioning Methods Dual Axis Plots
13. Deep Integration with Pandas & Seaborn
Pandas Plotting Backend Seaborn Overlays Passing Axes
14. 3D Plotting
3D Setup 3D Lines and Scatter Surface and Wireframes Camera View
15. Dynamic & Live Plots
Interactive Mode Animation Module Real-time Updates Exporting Animations
16. Performance Optimization & Interactive Backends
Plotting Speed Interactive Backends Event Handling

Line Plots in Matplotlib

In this lesson, you will learn how to create line plots using Matplotlib. You will understand how to plot data points, customize line styles, add markers, display multiple lines, and format your charts.

1. Learning Objectives

By the end of this lesson, you will be able to:

  • Understand what a line plot is and where it is used.
  • Create line plots using the Matplotlib plot() function.
  • Understand X-axis and Y-axis data values.
  • Customize line colours, width, styles, and markers.
  • Add chart titles, axis labels, grid lines, and legends.
  • Display multiple data series in a single line chart.
  • Save line plots in different file formats.

2. What Is a Line Plot?

A line plot is a type of chart that displays data points connected by straight lines. It is commonly used to show trends, patterns, and changes in values over a period of time.

In Matplotlib, the plot() function is used to create line plots. You provide X-axis and Y-axis values, and Matplotlib connects the corresponding data points.

Example: Monthly Sales Report

Suppose a company wants to understand its monthly sales. It has sales values for January, February, March, April, and May. A line plot can show how sales increase or decrease during these months.

The months are displayed on the X-axis, while the sales values are displayed on the Y-axis.

Monthly Sales Jan Feb Mar Apr May Month Sales
Figure 1: A line plot showing changes in monthly sales.

3. Basic Syntax of the plot() Function

The plot() function is the main function used to create a line chart. It accepts X-axis and Y-axis values as its basic arguments.

Syntax

import matplotlib.pyplot as plt

plt.plot(x, y)

plt.show()
Parameter Description
x Values displayed along the X-axis.
y Values displayed along the Y-axis.
plt.plot() Creates the line plot using the supplied data.
plt.show() Displays the created chart.
Tip: The X and Y data must have compatible lengths. Each X value is associated with a corresponding Y value.

4. Creating Your First Line Plot

Let's create a simple line plot using a list of days and their corresponding sales values.

Example: Weekly Sales

import matplotlib.pyplot as plt

days = ["Monday", "Tuesday", "Wednesday",
        "Thursday", "Friday"]

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

plt.plot(days, sales)

plt.title("Weekly Sales Report")
plt.xlabel("Days")
plt.ylabel("Sales")

plt.show()

Explanation:

  • We import pyplot from Matplotlib.
  • The days list contains X-axis values.
  • The sales list contains Y-axis values.
  • plot() creates the line chart.
  • title(), xlabel(), and ylabel() add chart information.
  • show() displays the chart.
Weekly Sales Report Monday Tuesday Wednesday Thursday Friday Days Sales
Figure 2: Weekly sales displayed as a line chart.

5. Customizing Line Colour and Width

Matplotlib allows you to customize the appearance of a line. You can change its colour and thickness using the color and linewidth parameters.

Example: Changing Colour and Width

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]

plt.plot(
    x,
    y,
    color="red",
    linewidth=3
)

plt.title("Customized Line Plot")
plt.show()
Parameter Description Example
color Changes the colour of the line. color="red"
linewidth Changes the thickness of the line. linewidth=3

6. Using Different Line Styles

The linestyle parameter controls the pattern of the line. Matplotlib supports solid, dashed, dotted, and dash-dot styles.

Solid (-) Dashed (--) Dotted (:) Dash-dot (-.)
Figure 3: Common line styles available in Matplotlib.
Line Style Value Description
Solid - A continuous line.
Dashed -- A line made of dashes.
Dotted : A line made of dots.
Dash-dot -. A combination of dashes and dots.

Example

plt.plot(
    x,
    y,
    color="green",
    linestyle="--",
    linewidth=2
)

plt.show()

7. Adding Markers to a Line Plot

Markers are symbols displayed at individual data points. They help identify the exact positions of values on a line chart.

Circle (o) Square (s) Triangle (^) Diamond (D)
Figure 4: Examples of common marker styles.
Marker Value Description
CircleoDisplays a circle marker.
SquaresDisplays a square marker.
Triangle^Displays a triangle marker.
Star*Displays a star marker.
Plus+Displays a plus marker.
DiamondDDisplays a diamond marker.

Example

plt.plot(
    x,
    y,
    marker="o",
    markersize=8,
    color="blue"
)

plt.show()

8. Adding Titles, Axis Labels, Grid, and Legend

A good chart should clearly explain the information it displays. Matplotlib provides functions to add titles, labels, grid lines, and legends.

Function Purpose
plt.title()Adds a title to the chart.
plt.xlabel()Adds a label to the X-axis.
plt.ylabel()Adds a label to the Y-axis.
plt.grid()Displays grid lines.
plt.legend()Displays the legend.

Example

import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May"]
revenue = [120, 150, 135, 180, 210]

plt.plot(
    months,
    revenue,
    color="blue",
    marker="o",
    label="Revenue"
)

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

plt.grid(True)
plt.legend()

plt.show()
Tip: Use meaningful chart titles and axis labels. A legend is especially useful when your chart contains multiple lines.

9. Plotting Multiple Lines

Matplotlib allows you to display more than one line in the same chart. You can call plot() multiple times and use different colours and labels to compare different data series.

Example: Comparing Product Sales

Suppose a company wants to compare the monthly sales of Product A and Product B. Both data series can be displayed in one chart.

import matplotlib.pyplot as plt

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

product_a = [100, 120, 150, 140, 180]
product_b = [90, 110, 130, 160, 170]

plt.plot(
    months,
    product_a,
    color="blue",
    marker="o",
    label="Product A"
)

plt.plot(
    months,
    product_b,
    color="red",
    marker="s",
    label="Product B"
)

plt.title("Product Sales Comparison")
plt.xlabel("Month")
plt.ylabel("Sales")

plt.legend()
plt.grid(True)

plt.show()
Product Sales Comparison Jan Feb Mar Apr May Product A Product B
Figure 5: Comparing two product sales series in one line chart.
Tip: Always provide a different label for each data series so that users can identify the lines easily.

10. Saving a Line Plot

After creating a chart, you can save it as an image or document using the savefig() function.

Example: Saving a Chart

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]

plt.plot(x, y, marker="o")
plt.title("My Line Chart")

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

plt.show()
Parameter Description
line_chart.png Name and file format of the saved chart.
dpi=300 Sets the output resolution.
bbox_inches="tight" Adjusts the saved bounding box to fit the chart content.
Important: Save the figure before calling plt.show() when using workflows where displaying the figure may close or clear it.

11. Common Mistakes While Creating Line Plots

Beginners may face some common problems while creating line charts. Understanding these issues helps you write correct Matplotlib code.

Common Mistake Solution
X and Y values have different lengths. Make sure both data sequences have compatible lengths.
Chart is not displayed. Call plt.show() in a normal Python script.
Legend is not visible. Provide labels in plot() and call plt.legend().
Chart is difficult to understand. Add a title, axis labels, and grid lines.
Multiple lines look similar. Use different colours, markers, or line styles.

12. Practical Activity

Task: Create a Monthly Temperature Chart

Create a line plot to display the temperature for six months. Follow the instructions below:

  1. Create a list containing six month names.
  2. Create a second list containing temperature values.
  3. Use plt.plot() to create the line chart.
  4. Set the line colour to red.
  5. Add circle markers to the data points.
  6. Add a chart title and axis labels.
  7. Enable grid lines and display the chart.
  8. Save the chart as temperature.png.

Starter Code

import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
temperature = [18, 21, 25, 30, 33, 29]

# Create your line plot here

plt.show()

13. Practice Questions

Test your understanding of line plots:

  1. What is a line plot?
  2. Which Matplotlib function is used to create a line plot?
  3. What is the purpose of X-axis and Y-axis values?
  4. How can you change the colour of a line?
  5. Which parameter controls the thickness of a line?
  6. What is the purpose of the marker parameter?
  7. Name four different line styles available in Matplotlib.
  8. How can you display multiple lines in one chart?
  9. What is the purpose of plt.legend()?
  10. Which function is used to save a line plot?

Summary

In this lesson, you learned how to create and customize line plots using Matplotlib. You explored the plot() function, X-axis and Y-axis values, line colours, line styles, markers, chart labels, legends, and multiple data series.

  • Use plt.plot() to create a line plot.
  • Use color and linewidth to customize line appearance.
  • Use linestyle to change the line pattern.
  • Use marker to highlight individual data points.
  • Use title(), xlabel(), and ylabel() to describe the chart.
  • Use grid() and legend() to improve chart readability.
  • Use savefig() to save the chart.
  • Use show() to display the chart.