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.
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. |
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.
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.
| Marker | Value | Description |
|---|---|---|
| Circle | o | Displays a circular marker. |
| Square | s | Displays a square marker. |
| Triangle | ^ | Displays an upward triangle. |
| Star | * | Displays a star marker. |
| Plus | + | Displays a plus marker. |
| Diamond | D | Displays 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.
plt.scatter(
x,
y,
color="blue",
alpha=0.5,
s=100
)
plt.show()
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()
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. |
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.
| 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. |
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.
- Create a list of study hours for ten students.
- Create a list of exam marks for the same students.
- Use plt.scatter() to display the data points.
- Set the marker colour to green.
- Set marker size to 100.
- Add a chart title and axis labels.
- Enable grid lines.
- 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:
- What is a scatter plot?
- Which Matplotlib function creates a scatter plot?
- What does each point represent in a scatter plot?
- What is the purpose of the s parameter?
- How can you change the shape of a marker?
- What is the purpose of the alpha parameter?
- How can you display multiple groups in one scatter plot?
- What is the purpose of the cmap parameter?
- What is the difference between a scatter plot and a line plot?
- 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.