Search code examples
pythonmatplotlibplotscatter-plot

How to plot scatterplot on top of solid line


I have two pairs of x and y values, one plotted as a line plot (blue), the other as a scatter plot (red). The points overlap, and the solid blue line is plotted on top of the red dots, causing only the non-overlapping portions of the red dots to be visible. I want this to be the other way around: I want the red dots to all be on top of the blue line so that the red dots are all completely visible, with the blue line being obscured at the points of overlap. Any suggestions for how to do this?

import numpy as np
import matplotlib.pyplot as plt


x1 = np.linspace(0,10,20)
x2 = np.linspace(0,10,500)

y1 = np.sin(x1)
y2 = np.sin(x2)

plt.plot(x2,y2, color = 'b')
plt.scatter(x1,y1,marker = 'o', s = 6, color = 'r')

enter image description here


Solution

  • You could use zorder.

    import numpy as np
    import matplotlib.pyplot as plt
    
    
    x1 = np.linspace(0,10,20)
    x2 = np.linspace(0,10,500)
    
    y1 = np.sin(x1)
    y2 = np.sin(x2)
    
    plt.plot(x2,y2, color = 'b', zorder=0)
    plt.scatter(x1,y1,marker = 'o', s = 6, color = 'r', zorder=1)
    
    plt.show()
    

    plot