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:
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():
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:
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:
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 |