Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Improper rendering at axes border in Matplotlib

I want to render a rectangle within an axes in matplotlib. The axes is the unit square with the origin at the bottom left corner. For the case where the rectangle is the same size as the axes - I want the rectangle to appear as though it is the border of the axes.

The problem is that it appears that the rendering is incorrect. The left (x=0) and top (y=1) of the rectangle get rendered, but the bottom (y=0), and right (x=1) do not show up.

Note: This is not specific to only rectangles ... it remains true for lines as well. The resulting rendering appears as:

Improper rectangle rendering.

The following code snippet demonstrates the problem:

import matplotlib.pyplot as mpl

r = mpl.Rectangle((0,0), 1, 1, edgecolor='red', facecolor='none', zorder=100)

axes = mpl.gca()
axes.add_patch(r)
axes.set_xbound(0, 1)
axes.set_ybound(0, 1)

axes.get_xaxis().set_visible(False)
axes.get_yaxis().set_visible(False)

[spine.set_visible(False) for spine in axes.spines.values()]

mpl.show()

I have also rendered to PDF and verified that this works correctly (for example when zooming in all sides are present).

This seemingly has to do with how the underlying image gets rasterized to the screen. Is there a way around this issue?

like image 889
Rocketman Avatar asked Sep 03 '26 15:09

Rocketman


1 Answers

The exact behavior is backend dependent (Your example works as you'd like it to on my system.)

However, if you turn clipping off for your rectangle, it should behave as you want on any backend.

In your example above, just do r.set_clip_on(False).

import matplotlib.pyplot as plt

r = plt.Rectangle((0,0), 1, 1, edgecolor='red', facecolor='none', zorder=100)

ax = plt.gca()
ax.add_patch(r)
ax.axis([0, 1, 0, 1])

ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)

[spine.set_visible(False) for spine in ax.spines.values()]

r.set_clip_on(False)

plt.show()

enter image description here

like image 118
Joe Kington Avatar answered Sep 05 '26 05:09

Joe Kington



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!