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

Scatter Plots in Matplotlib

In this lesson, you will learn how to create scatter plots using Matplotlib. You will understand how to display individual data points, customize markers, use colours and sizes, and identify relationships between variables.

1. Learning Objectives

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

  • Understand what a scatter plot is and where it is used.
  • Create scatter plots using the scatter() function.
  • Understand X-axis and Y-axis data values.
  • Customize marker colours, sizes, shapes, and transparency.
  • Display multiple groups of data in one scatter plot.
  • Use colour mapping to represent additional data values.
  • Add titles, axis labels, legends, and grid lines.
  • Save scatter plots in different file formats.

2. What Is a Scatter Plot?

A scatter plot is a type of chart that displays individual data points using markers on a two-dimensional coordinate system. Each point represents the relationship between two numerical variables.

In Matplotlib, the scatter() function is used to create scatter plots. Unlike a line plot, a scatter plot does not automatically connect the data points with lines.

Example: Student Study Hours and Exam Marks

Suppose a teacher wants to understand the relationship between students' study hours and their exam marks.

The number of study hours is displayed on the X-axis, and the exam marks are displayed on the Y-axis. Each dot represents one student.

Study Hours vs Exam Marks 1 3 5 7 9 Study Hours Exam Marks
Figure 1: A scatter plot showing the relationship between study hours and exam marks.

3. Basic Syntax of the scatter() Function

The scatter() function accepts X-axis and Y-axis values and displays each pair as an individual marker.

Syntax

import matplotlib.pyplot as plt

plt.scatter(x, y)

plt.show()
Parameter Description
x Numerical values displayed along the X-axis.
y Numerical values displayed along the Y-axis.
plt.scatter() Creates a scatter plot using individual markers.
plt.show() Displays the created chart.
Tip: X and Y data should have compatible lengths. Each X value is paired with its corresponding Y value.

4. Creating Your First Scatter Plot

Let's create a simple scatter plot to display the relationship between students' study hours and exam marks.

Example: Study Hours and Exam Marks

import matplotlib.pyplot as plt

study_hours = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

exam_marks = [35, 40, 45, 50, 55, 60, 65, 72, 80, 88]

plt.scatter(study_hours, exam_marks)

plt.title("Study Hours vs Exam Marks")
plt.xlabel("Study Hours")
plt.ylabel("Exam Marks")

plt.show()

Explanation:

  • We import pyplot from Matplotlib.
  • The study_hours list contains X-axis values.
  • The exam_marks list contains Y-axis values.
  • scatter() displays each pair as a separate marker.
  • title(), xlabel(), and ylabel() add chart information.
  • show() displays the scatter plot.
Study Hours vs Exam Marks 1 3 5 7 9 Study Hours Exam Marks
Figure 2: Individual student records represented as scatter points.

5. Customizing Marker Colours and Sizes

Matplotlib provides several parameters to customize the appearance of scatter plot markers. You can change their colour, size, edge colour, and transparency.

Example: Custom Marker Appearance

import matplotlib.pyplot as plt

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

plt.scatter(
    x,
    y,
    color="red",
    s=100,
    edgecolors="black",
    alpha=0.8
)

plt.title("Customized Scatter Plot")
plt.show()
Parameter Description Example
color Sets the marker colour. color="red"
s Sets marker size in points squared. s=100
edgecolors Sets the marker boundary colour. edgecolors="black"
alpha Controls marker transparency. alpha=0.8

6. Using Different Marker Styles

You can change the shape of markers using the marker parameter. Different marker styles help distinguish groups of data points.

Circle (o) Square (s) Triangle (^) Diamond (D)
Figure 3: Common marker shapes used in scatter plots.
Marker Value Description
CircleoDisplays a circular marker.
SquaresDisplays a square marker.
Triangle^Displays an upward triangle.
Star*Displays a star marker.
Plus+Displays a plus marker.
DiamondDDisplays a diamond marker.

Example

plt.scatter(
    x,
    y,
    marker="s",
    s=100,
    color="green"
)

plt.show()

7. Understanding Transparency with alpha

The alpha parameter controls the transparency of scatter plot markers. Its value ranges from 0 to 1.

alpha = 1.0 alpha = 0.5 alpha = 0.2 Fully visible Partially transparent Highly transparent
Figure 4: Different alpha values applied to scatter markers.
plt.scatter(
    x,
    y,
    color="blue",
    alpha=0.5,
    s=100
)

plt.show()
Tip: Transparency is useful when many data points overlap. It helps you identify areas with a higher concentration of points.

8. Plotting Multiple Groups of Data

You can display multiple groups in one scatter plot by calling scatter() more than once. Different colours and marker styles help distinguish each group.

Example: Comparing Two Student Groups

import matplotlib.pyplot as plt

group_a_hours = [2, 3, 4, 5, 6]
group_a_marks = [40, 45, 55, 60, 65]

group_b_hours = [3, 4, 5, 6, 7]
group_b_marks = [50, 60, 65, 75, 85]

plt.scatter(
    group_a_hours,
    group_a_marks,
    color="blue",
    label="Group A"
)

plt.scatter(
    group_b_hours,
    group_b_marks,
    color="red",
    marker="s",
    label="Group B"
)

plt.title("Student Group Comparison")
plt.xlabel("Study Hours")
plt.ylabel("Exam Marks")

plt.legend()
plt.grid(True)

plt.show()
Student Group Comparison 2 3 4 5 6 Group A Group B
Figure 5: Two groups of students displayed in one scatter plot.
Tip: Use meaningful labels and different marker styles to make each data group easy to identify.

9. Using Colours to Represent Data Values

The c parameter allows you to assign colours based on numerical values. You can also use the cmap parameter to select a colormap. This helps represent an additional variable through colour.

Example: Colour Mapping

import matplotlib.pyplot as plt

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

values = [10, 20, 30, 40, 50, 60]

plt.scatter(
    x,
    y,
    c=values,
    cmap="viridis",
    s=120
)

plt.colorbar(label="Data Values")

plt.title("Scatter Plot with Colour Mapping")
plt.xlabel("X Values")
plt.ylabel("Y Values")

plt.show()
Parameter Purpose
c Provides values used to determine marker colours.
cmap Selects the colormap used for numerical values.
plt.colorbar() Displays a colour scale for interpreting the values.
Important: When using c with numerical values, make sure the values correspond to the plotted data points.

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

Titles and labels explain the information shown in a scatter plot. Grid lines make it easier to estimate point positions, while legends identify different data groups.

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

Example

import matplotlib.pyplot as plt

height = [150, 155, 160, 165, 170, 175]
weight = [45, 48, 52, 55, 60, 68]

plt.scatter(
    height,
    weight,
    color="purple",
    label="Students"
)

plt.title("Student Height and Weight")
plt.xlabel("Height (cm)")
plt.ylabel("Weight (kg)")

plt.grid(True)
plt.legend()

plt.show()

11. Scatter Plot vs Line Plot

Both scatter plots and line plots display numerical data using X-axis and Y-axis values. However, they are used for different purposes.

Scatter Plot Line Plot Individual data points Connected data points
Figure 6: Visual comparison of scatter plots and line plots.
Feature Scatter Plot Line Plot
Function plt.scatter() plt.plot()
Display Individual data points. Data points connected by lines.
Main Purpose Study relationships and distributions. Show trends and changes.
Common Use Comparing two numerical variables. Showing changes over time.

12. Saving a Scatter Plot

After creating a scatter plot, you can save it using the savefig() function. Matplotlib supports formats such as PNG, JPEG, SVG, and PDF.

Example: Saving a Scatter Plot

import matplotlib.pyplot as plt

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

plt.scatter(x, y, color="blue")

plt.title("My Scatter Plot")

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

plt.show()
Parameter Description
scatter_plot.png Name and 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.

13. Common Mistakes While Creating Scatter Plots

Beginners may face common problems while creating scatter plots. 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.
Markers are too small or too large. Adjust the s parameter.
Points overlap and are difficult to read. Use the alpha parameter to add transparency.
Different groups are difficult to identify. Use different colours and labels.
Chart is not displayed. Call plt.show() in a normal Python script.
Colour values are not matching data points. Provide a compatible sequence of colour values.

14. Practical Activity

Task: Create a Student Performance Scatter Plot

Create a scatter plot to show the relationship between students' study hours and exam marks.

  1. Create a list of study hours for ten students.
  2. Create a list of exam marks for the same students.
  3. Use plt.scatter() to display the data points.
  4. Set the marker colour to green.
  5. Set marker size to 100.
  6. Add a chart title and axis labels.
  7. Enable grid lines.
  8. Save the chart as student_performance.png.

Starter Code

import matplotlib.pyplot as plt

study_hours = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

exam_marks = [35, 40, 45, 50, 55, 60, 65, 72, 80, 88]

# Create your scatter plot here

plt.show()

15. Practice Questions

Test your understanding of scatter plots:

  1. What is a scatter plot?
  2. Which Matplotlib function creates a scatter plot?
  3. What does each point represent in a scatter plot?
  4. What is the purpose of the s parameter?
  5. How can you change the shape of a marker?
  6. What is the purpose of the alpha parameter?
  7. How can you display multiple groups in one scatter plot?
  8. What is the purpose of the cmap parameter?
  9. What is the difference between a scatter plot and a line plot?
  10. Which function is used to save a scatter plot?

16. Lesson Summary

In this lesson, you learned how to create scatter plots using Matplotlib. You explored the scatter() function, X-axis and Y-axis values, marker customization, transparency, multiple data groups, colour mapping, and chart formatting.

  • Use plt.scatter() to create scatter plots.
  • Use X and Y values to position individual data points.
  • Use color to customize marker colours.
  • Use s to control marker size.
  • Use marker to change marker shapes.
  • Use alpha to control transparency.
  • Use c and cmap for colour mapping.
  • Use title(), xlabel(), and ylabel() to describe the chart.
  • Use legend() to identify different data groups.
  • Use savefig() to save the chart.

You are now ready to create scatter plots and explore relationships between numerical variables using Matplotlib.