1

Given the following example code, which draws an ellipse, how can I make the grid lines appear behind everything else?

#!/usr/bin/python3
from pylab import *
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
grid()
ax.add_artist( Ellipse( xy = (0,0), width = 1, height = 2, angle = 0, edgecolor='b', lw=4, facecolor='green' ) )
show()

The answers on this website to similar questions haven't worked in my case. Can you give a complete working example?

WVJoe
  • 515
  • 7
  • 21
shuhalo
  • 5,732
  • 12
  • 43
  • 60
  • 1
    ["pylab is deprecated and its use is strongly discouraged because of namespace pollution. Use pyplot instead."](https://matplotlib.org/3.1.1/tutorials/introductory/usage.html) – Mr. T Feb 06 '21 at 19:01
  • Does this answer your question? [How to draw grid lines behind matplotlib bar graph](https://stackoverflow.com/questions/23357798/how-to-draw-grid-lines-behind-matplotlib-bar-graph) – Mr. T Feb 06 '21 at 19:06

1 Answers1

2

You need to utilize the zorder argument. Make this modification and it will work.

ax.add_artist( Ellipse( xy = (0,0), width = 1, height = 2, angle = 0, edgecolor='b', lw=4, facecolor='green' ,zorder=2) )

Anytime you are plotting multiple items, you can control the order they appear with zorder. Find more information on zoder here.

This simple fix makes the figure go from this:

Grid in front

to this:

Grid behind

WVJoe
  • 515
  • 7
  • 21