sebo
sebo

Reputation: 1664

How can you put a matplotlib artist in the background to overlay a plot on top?

I know I'm missing something very basic about how matplotlib organizes figures and plots, but I've searched the documentation with no result. I have narrowed down my question to something simple that will hopefully help me understand matplotlib a little better.

Given the following piece of code:

x_coords = [1,2,3]
y_coords = [2,3,4]
labels = ['A','B','C']
plt.scatter(x_coords, y_coords, marker = 'o')
for l, x, y in zip(labels, x_coords, y_coords):
    plt.annotate(l, xy=(x,y), xytext=(-10,5), textcoords='offset points')

circle = plt.Circle((2,3), 1.5, color='w', ec='k')
fig = plt.gcf()
fig.gca().add_artist(circle)

plt.show()

The circle gets drawn on a layer between the markers and labels of the plotted points. How can I control which layers these elements are drawn on?

Here is the drawn image for a visual reference:

simple plot

Upvotes: 4

Views: 3444

Answers (1)

sodd
sodd

Reputation: 12923

First of all, the circle in your code is not a Figure, it is an Artist, more specifically a Patch. In matplotlib, a Figure is a top-level Artist which contains other elements, so your title is a bit misleading.

Second, you can place the circle below the other artists by specifying its zorder kwarg:

circle = plt.Circle((2,3), 1.5, color='w', ec='k', zorder=0)

The artist with the lowest zorder gets drawn on the bottom layer, and the one with the highest gets drawn on top.

enter image description here

Upvotes: 7

Related Questions