Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw Circles on Top Level of Figure

I'm working on a figure where I'm trying to draw a circle on top of a combination colormap and contour plot. The circle keeps getting drawn under the contours instead of on top of them (see the figure below). I've tried reordering how I call imshow, contour, and Circle to see if I can get the circle to display on top, but I haven't had any luck. Is there a way to force Circle to be on the top most level of the figure? Thanks for your help!

Colormap with contour plot and added circle

like image 389
Matt Avatar asked Jan 13 '17 15:01

Matt


2 Answers

Use the zorder kwarg. That controls which elements go on top of each other. So, in this case, you want to increase the zorder of the circle. You may need to experiment to find a zorder that gives you the result you require, but the rule is that higher zorder objects appear on top of lower zorder objects.

Its hard to know exactly without any of your code, but assuming you've used pcolormesh, contour and a Circle patch, this example shows the effect of not setting a zorder (white circle), and setting zorder=10 (red circle).

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle

# Fake data
x = np.arange(100)
y = np.arange(100)
X, Y = np.meshgrid(x, y)
z = X**0.5 * Y**0.5

fig, ax = plt.subplots(1)
ax.set_aspect('equal')

ax.pcolormesh(X, Y, z, cmap='viridis')
ax.contour(X, Y, z, colors='k', linewidths=3)

circ1 = Circle((65, 65), 30, facecolor='None', edgecolor='w', lw=5)
circ2 = Circle((35, 35), 30, facecolor='None', edgecolor='r', lw=5, zorder=10)

ax.add_patch(circ1)
ax.add_patch(circ2)

plt.show()

Note that the white circle lies beneath the black contour lines, but by increasing the zorder to 10, the red circle lies on top of the contour lines.

enter image description here

like image 191
tmdavison Avatar answered Oct 11 '22 10:10

tmdavison


You can set the zorder property of the plot object to force it to be on top of other plots within the same axes. A higher zorder value will appear on top of a lower zorder value.

plt.plot([1, 2], [1, 2], zorder=100)

By default, patches have a zorder of 1, 2D line objects have a zorder of 2 and text has a zorder of 3.

like image 37
Suever Avatar answered Oct 11 '22 12:10

Suever