How to create a simple scatter plot using matplotlib ?

April 03, 2019    /    Viewed: 7728    /    Comments: 0    /    Edit


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 ?

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 ?

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 ?

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 ?

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

Links Site
matplotlib.pyplot.scatter Matplotlib doc
scatter plot in matplotlib stackoverflow
Nuage de points (statistique) Wikipedia
pylab_examples example code: scatter_demo.py Matplotlib Doc
pylab_examples example code: scatter_star_poly.py Matplotlib Doc
matplotlib scatter plot legend stackoverflow
Matplotlib Python Scatter Plot [duplicate] stackoverflow


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!