How to create a simple scatter plot using matplotlib ?

Published: April 03, 2019

DMCA.com Protection Status

Simples examples of how to create a simple scatter plot using matplotlib

Scatter plot with matplotlib

To plot a scatter plot with matplotlib, ta solution is to use the method scatter from the class pyplot, example:

How to create a simple scatter plot using matplotlib ?
How to create a simple scatter plot using matplotlib ?

import matplotlib.pyplot as plt

x = [1,2,3,4,5,6,7,8]
y = [4,1,3,6,1,3,5,2]

plt.scatter(x,y)

plt.title('Nuage de points avec Matplotlib')
plt.xlabel('x')
plt.ylabel('y')

plt.savefig('ScatterPlot_01.png')
plt.show()

Increase the point size

It is possible to increase the point size by specifying the argument s (size) in the function scatter():

How to create a simple scatter plot using matplotlib ?
How to create a simple scatter plot using matplotlib ?

import matplotlib.pyplot as plt

x = [1,2,3,4,5,6,7,8]
y = [4,1,3,6,1,3,5,2]
size = [100,500,100,500,100,500,100,500]

plt.scatter(x,y,s=size)

plt.title('Nuage de points avec Matplotlib')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig('ScatterPlot_02.png')
plt.show()

Note: to change the size of all the points, just do s = 300 for example.

Change the color

To change the color there is the argument c in the function scatter(), example:

How to create a simple scatter plot using matplotlib ?
How to create a simple scatter plot using matplotlib ?

import matplotlib.pyplot as plt

x = [1,2,3,4]
y = [4,1,3,6]
size = [100,500,100,500]

plt.scatter(x, y, s=size, c='coral')

x = [5,6,7,8]
y = [1,3,5,2]
size = [100,500,100,500]

plt.scatter(x, y, s=size, c='lightblue')

plt.title('Nuage de points avec Matplotlib')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig('ScatterPlot_03.png')
plt.show()

Add a legend

Finally, it also possible to add a legend:

How to create a simple scatter plot using matplotlib ?
How to create a simple scatter plot using matplotlib ?

import matplotlib.pyplot as plt

x = [1,2,3,4]
y = [4,1,3,6]
size = [100,500,100,500]

plt.scatter(x, y, s=size, c='coral', label='class 1')

x = [5,6,7,8]
y = [1,3,5,2]
size = [100,500,100,500]

plt.scatter(x, y, s=size, c='lightblue', label='class 2')

plt.legend()

plt.title('Nuage de points avec Matplotlib')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig('ScatterPlot_04.png')
plt.show()

References

Image

of