Matplotlib – Scatter Plot

Matplotlib – Scatter Plot

In this tutorial, we’ll learn how to create a scatter plot using Matplotlib in Python.

A scatter plot is useful for visualizing the relationship between two sets of data points.

The following is a step by step tutorial on how to draw a Scatter Plot using Matplotlib.

1. Import Necessary Libraries

Begin by importing Matplotlib library.

import matplotlib.pyplot as plt

Optionally, you can also import NumPy for generating sample data.

import numpy as np

2. Sample Data

Create two arrays of data points for the X and Y axes.

# Create arrays for X and Y
x_values = [4, 2, 3, 9, 1, 4, 1, 5, 8]
y_values = [1, 8, 4, 2, 3, 7, 3, 6, 5]

3. Create Scatter Plot

Use Matplotlib’s scatter() function to create a scatter plot with the generated data points.

# Create scatter plot
plt.scatter(x_values, y_values, label='Scatter Plot')

4. Customize and Show the Plot

Customize the plot by adding a title, labels for the X and Y axes, and a legend. Finally, display the plot using show().

# Customize the plot
plt.title('Scatter Plot Example')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend()

# Show the plot
plt.show()

Complete Program for Scatter Plot

Here’s the complete program to draw a Scatter Plot using Matplotlib.

Python Program

import matplotlib.pyplot as plt
import numpy as np

# Number of data points
num_points = 50

# Create arrays for X and Y
x_values = [4, 2, 3, 9, 1, 4, 1, 5, 8]
y_values = [1, 8, 4, 2, 3, 7, 3, 6, 5]

# Create scatter plot
plt.scatter(x_values, y_values, label='Scatter Plot')

# Customize the plot
plt.title('Scatter Plot Example')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend()

# Show the plot
plt.show()

Output

Matplotlib - Scatter Plot - Example

Summary

This tutorial covered the basics of creating a scatter plot using Matplotlib in Python.

Code copied to clipboard successfully 👍