Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round connection for Matplotlib axis spines

This is a fairly simple question. I am working on creating a Matplotlib figure that has several inset axes.

I have removed the tick marks so that the inset spines of each of the inset axes meet at a 90 degree angle. However, when you add a legend to this figure, it adds a legend object that has slightly rounded spine connections for each "edge" of the legend object.

Is there an easy way to get a similar effect for the spines of an inset axis or axis more generally?

My code:

fig, e = plt.subplots(figsize=(10, 5))
    
a = e.inset_axes([.1, .1, .1, .2])
b = e.inset_axes([.3, .1, .1, .2])

for ax in [a, b]:
    
    ax.set_yticks([])
    ax.set_xticks([])

Current output:

enter image description here

Desired output:

enter image description here


1 Answers

An idea is to hide the spines, and draw a FancyBboxPatch at the same spot. Setting clip_on=False avoids that the box would be clipped inappropriately.

Assigning the rounded box to the ax_a.patch makes the clipping both of the main ax and of the objects inside the inset ax work.

Here is example code modifying the left inset axis.

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

fig, ax_e = plt.subplots(figsize=(10, 5))

ax_a = ax_e.inset_axes([.1, .1, .1, .2])
ax_b = ax_e.inset_axes([.3, .1, .1, .2])

for ax in [ax_a, ax_b]:
    ax.set_yticks([])
    ax.set_xticks([])
for s in ax_a.spines:
    ax_a.spines[s].set_visible(False)
p_bbox = FancyBboxPatch((0, 0), 1, 1,
                        boxstyle="round,pad=-0.0040,rounding_size=0.2",
                        ec="black", fc="white", clip_on=False, lw=1,
                        mutation_aspect=1,
                        transform=ax_a.transAxes)
ax_a.add_patch(p_bbox)
ax_a.patch = p_bbox

t = np.linspace(0, 2 * np.pi, 100)
ax_a.plot(np.sin(3 * t), np.sin(4 * t))  # drawing some curve
ax_a.plot([-2, 2], [-2, 2], 'g', lw=10, alpha=0.3)  # diagonal line to check the clipping in the corners
ax_a.set_xlim(-1.1, 1.1)
ax_a.set_ylim(-1.1, 1.1)

ax_e.set_facecolor('tomato')  # show the clipping around the inset axes

plt.show()

inset axis with rounded corners

like image 111
JohanC Avatar answered May 04 '26 22:05

JohanC



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!