64

Does anyone know a way to bring a scatter plot to the foreground in matplotlib? I have to display the scatter plotting on top of the contour, but by default it is plotted underneath...

feetwet
  • 3,248
  • 7
  • 46
  • 84
Mike
  • 1,561
  • 3
  • 15
  • 18
  • 7
    Check out the [`zorder`](http://matplotlib.org/api/artist_api.html#matplotlib.artist.Artist.set_zorder) parameter of the `scatter` method. [Example usage](http://matplotlib.org/examples/pylab_examples/zorder_demo.html) from the matplotlib site. – sodd Jul 02 '13 at 16:59

1 Answers1

94

You can manually choose in which order the different plots are to be displayed with the zorder parameter of e.g. the scatter method.

To demonstrate, see the code below, where the scatter plot in the left subplot has zorder=1 and in the right subplot it has zorder=-1. The object with the highest zorder is placed on top. This means that the scatter will be placed on top of the contour in the first subplot, while it is placed underneath in the second subplot.

import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = 10.0 * (Z2 - Z1)

norm = cm.colors.Normalize(vmax=abs(Z).max(), vmin=-abs(Z).max())
cmap = cm.PRGn

levels = np.arange(-2.0, 1.601, 0.4)

fig, axes = plt.subplots(1,2, sharey=True)

for ax, zord in zip(axes, [1, -1]):
    ax.contourf(X, Y, Z, levels,
                cmap=cm.get_cmap(cmap, len(levels)-1),
                norm=norm)
    ax.autoscale(False) # To avoid that the scatter changes limits
    ax.scatter(np.random.uniform(-3,3,10),
               np.random.uniform(-2,2,10),
               zorder=zord)
    ax.set_title('Scatter with zorder={0}'.format(zord))

enter image description here

sodd
  • 12,482
  • 3
  • 54
  • 62
  • 3
    Thanks for the answer. What's missing is the reference point for zorder. What are the default zorder values for different plot functions? – Dr_Zaszuś Jan 15 '19 at 16:34
  • 3
    @Dr_Zaszuś The default values are described on [this page](https://matplotlib.org/3.1.1/gallery/misc/zorder_demo.html). Filled contours are "patches" and have default zorder `1`, while scatter plots are "collections" and also have default zorder `1`. The OP probably called `contourf` *after* calling `scatter` -- when zorders are identical they are plotted in the order in which they were created. – Luke Davis May 17 '20 at 01:34