Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grid zorder seems not to take effect (matplotlib)

I am trying to to plot scatter points on a grid using python's matplotlib (1.4.3 but tried on other versions without success too). Everything works except the grid zorder position. I set grid's zorder to be lower that that of scatter but the grid still covers the scatter points.

Here is a simple code to reproduce the problem:

import numpy as np
from matplotlib import pyplot as plt

# create points
pnts = np.array([[1., 1.], [1., 1.2]])

# create figure
plt.grid(True, linestyle='-', color='r', zorder=1)
plt.scatter(pnts[:,0], pnts[:,1], zorder=2)
plt.ylim([0, 2])
plt.xlim([0, 2])
plt.savefig('testfig.png', dpi=350)

I get this:
If you zoom in on the dots, you can see the grid is on top, although it has lower zorder: enter image description here

Is this a bug or am I doing something wrong?

like image 985
mmagnuski Avatar asked Jul 19 '15 21:07

mmagnuski


People also ask

What does PLT grid () do in Python?

pyplot. grid() Function. The grid() function in pyplot module of matplotlib library is used to configure the grid lines.


2 Answers

In case anyone is still wondering about this years later (like myself), this is a long standing issue (Sept 2015):

Axes.grid() not honoring specified "zorder" kwarg

Quoting the issue:

Axes.grid() is not honoring a provided custom zorder. Instead the grid's zorder seems to be fixed at some miraculous value in between 2.5 and 2.6 (I could not find a key for grid zorder in rcParams).

Apparently the only solution so far is to:

just add 2.5 to all of your z-orders.

There's also an old answer in this question Matplotlib: draw grid lines behind other graph elements but it does not seem to work anymore.

like image 77
Gabriel Avatar answered Oct 23 '22 19:10

Gabriel


The following works for me:

ax.set_axisbelow(True)

From the "Notes" section in the docs for Axes.grid:

The axis is drawn as a unit, so the effective zorder for drawing the grid is determined by the zorder of each axis, not by the zorder of the Line2D objects comprising the grid. Therefore, to set grid zorder, use set_axisbelow or, for more control, call the set_zorder method of each axis.

The default value for this setting is

>>> import matplotlib as mpl
>>> mpl.rcParams["axes.axisbelow"]
'line'

According to the docs for Axes.set_axisbelow the possible values are:

  • True (zorder = 0.5): Ticks and gridlines are below all Artists.
  • 'line' (zorder = 1.5): Ticks and gridlines are above patches (e.g. rectangles, with default zorder = 1) but still below lines and markers (with their default zorder = 2).
  • False (zorder = 2.5): Ticks and gridlines are above patches and lines / markers.
like image 3
Stan Avatar answered Oct 23 '22 20:10

Stan