How to plot points in front of a line in matplotlib ?

Published: April 12, 2019

DMCA.com Protection Status

By default in matplotlib, if a line and a scatter plot are plotted in a same figure, the points are placed behind the line, illustration (no matter if the scatter() is called before plot()):

How to plot points in front of a line in matplotlib ?
How to plot points in front of a line in matplotlib ?

import matplotlib.pyplot as plt

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

plt.plot([0,10],[0,10])
plt.scatter(x,y,s=300,color='red')

plt.title("Tracer un nuage de points devant une droite")
plt.grid()

plt.savefig("scatter_points_order_01.png", bbox_inches='tight')
plt.show()
plt.close()

To put the points above the line, a solution is to use the option zorder, like here:

How to plot points in front of a line in matplotlib ?
How to plot points in front of a line in matplotlib ?

import matplotlib.pyplot as plt

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

plt.plot([0,10],[0,10],zorder=1)
plt.scatter(x,y,s=300,color='red',zorder=2)

plt.title("Tracer un nuage de points devant une droite")
plt.grid()

plt.savefig("scatter_points_order_02.png", bbox_inches='tight')
plt.show()

References

Image

of