Home » Programming » Python » Scatter Plot Python

Python Scatter Plots with Matplotlib [Tutorial]

Graphs are awesome. If you disagree, you probably shouldn’t read on.

The best (and easiest!) way to create graphs and scatter plots in Python is using the package Matplotlib. This tutorial explains exactly how to do so.

https://pypi.org/project/matplotlib/

What is matplotlib? I’ll let them introduce themselves in their own words:

Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python.

This article will give you a jump-start on using Matplotlib to create scatter plots.

Install Python Dependencies

First, you’ll need to install MatplotLib using the pip Python package manager.

pip3 install matplotlib numpy

NumPy is also installed – it’ll be used to generate some random number sets to plot.

Don’t have pip installed?

Here’s how to install Pip!

Make a Simple Scatter Plot in Python

# Import dependencies
import numpy
import matplotlib.pyplot as plot

# Generate random data
# The x and y coordinates will be paired based on their corresponding position in each list
numberOfPoints = 200 # The number of points we want to plot

x = numpy.random.rand(numberOfPoints) # Generate list of random X coordinates
y = numpy.random.rand(numberOfPoints)# Generate list of random Y coordinates

# Draw the plot using Matplotlib!
# Plot colour, shapes, etc will all be the default
plot.scatter(x, y)
plot.title('Making Plots with Python!')
plot.xlabel('x value')
plot.ylabel('y Value')

# Display the plot in a GUI window
plot.show()

Save the above code in the file scatter.py, and run it using:

python3 scatter.py
Making Scatter Plots with Python!
Making Scatter Plots with Python!

And you’ll see the following:

Simple! And Matplotlib has done most of the legwork for us.

Saving the Graph

Matplotlib even gives you a simple way to tweak and export the graph as an image using the buttons at the bottom of the window.

Resize and align your graph and export it for use on the web or in print.

Advanced Usage – Coloured Groups and Setting Point Size

# Import dependencies
import numpy
import matplotlib.pyplot as plot

# Generate random data
# The x and y coordinates will be paired based on their corresponding position in each list
numberOfPoints = 200

x = numpy.random.rand(numberOfPoints) # Generate list of random X coordinates
y = numpy.random.rand(numberOfPoints) # Generate list of random Y coordinates

# Split the random X/Y pairs into groups by taking slices from the lists and combining them into arrays
group1 = (x[0:50], y[0:50]) # The first group is the first 51 random generated X/Y pairs (51 as list indexes start counting at 0)
group2 = (x[51:102], y[51:102]) # The second group is the next 51 random generated X/Y pairs
group3 = (x[103:199], y[103:199]) # And group three is the rest

# Combine the groups into one data set
data = (group1, group2, group3)

# Name and colour the groups
# Name and colour will be matched together with the group by the order they are presented
colours = ("red", "green", "blue")
groups = ("Cherries", "Apples", "Blueberries")

# Draw the Plot
figure = plot.figure()
axis = figure.add_subplot(1, 1, 1)# Add subplot to plot our data on - the numbers represent the position of the graph

for data, colour, group in zip(data, colours, groups): # The zip function is used to pair the data, colours, and groups based on their order in their respective lists
    # Iterate through this paired data/colour/group information and use it to add points to the scatter plot
    x, y = data # Assigns the X, Y values generated earlier to the variables x and y
    axis.scatter(x, y, alpha=0.5, c=colour, edgecolors='none', s=30, label=group) # alpha represents point transparency, edgecolours the border to the plotted points, s is the size of the points, and label labels the plots by their group

plot.title('Making Plots with Python!')
plot.xlabel('x value')
plot.ylabel('y Value')
    
plot.legend(loc=1) # Show the legend in the top-right corner

# Display the plot in a GUI window
plot.show()

Result:

Python Scatter Plot Results
Python Scatter Plot Results

Conclusion

Why not see if you can read and plot the data from a file to test your Python skills?

Matplotlib also supports a long list of other graphs and mathematical functions – go explore!

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment