Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increase Axis Thickness in Matplotlib (Without Cutting into Plot Domain!)

I am interested in a way to increase the thickness of the axes in matplotlib (without cutting into the domain of the plot). That is, I want the thickness of the axes to extend outwards from the plot, rather than inwards. Is such a thing possible?

Traditional methods (e.g., see below) do not seem to work:

from pylab import *

close("all")
#rc('axes', linewidth=30)

# Make a dummy plot
plot([0.01, 0, 1], [0.5, 0, 1])

fontsize = 14
ax = gca()

for axis in ['top','bottom','left','right']:
  ax.spines[axis].set_linewidth(30)

xlabel('X Axis', fontsize=16, fontweight='bold')
ylabel('Y Axis', fontsize=16, fontweight='bold')
like image 756
grover Avatar asked May 26 '26 12:05

grover


1 Answers

An option to have the same effect would be to create a white rectangle with exactly the axes extent, such that the part of the spines that is inside the axes is hidden by the rectangle. This would then require to make the linewidth twice as large because only half of the line is seen.

import matplotlib.pyplot as plt

# Make a dummy plot
fig, ax = plt.subplots()
ax.plot([0.01, 0, 1], [0.5, 0, 1], zorder=1)

ax.axis([0,1,0,1])


for axis in ['top','bottom','left','right']:
    ax.spines[axis].set_linewidth(30)
    ax.spines[axis].set_color("gold")
    ax.spines[axis].set_zorder(0)

ax.add_patch(plt.Rectangle((0,0),1,1, color="w", transform=ax.transAxes))


ax.set_xlabel('X Axis', fontsize=16, fontweight='bold')
ax.set_ylabel('Y Axis', fontsize=16, fontweight='bold')

plt.show()

I made the spines yellow here such that they do not hide the ticks and ticklabels.

enter image description here

Another option is to adapt the answer from Set matplotlib rectangle edge to outside of specified width? to create a rectangle which is strictly enclosing an area in the plot like this:

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib.offsetbox import AnnotationBbox, AuxTransformBox

# Make a dummy plot
fig, ax = plt.subplots()
ax.plot([0.01, 0, 1], [0.5, 0, 1], zorder=1)

ax.axis([0,1,0,1])

linewidth=14
xy, w, h = (0, 0), 1, 1
r = Rectangle(xy, w, h, fc='none', ec='k', lw=1, transform=ax.transAxes)

offsetbox = AuxTransformBox(ax.transData)
offsetbox.add_artist(r)
ab = AnnotationBbox(offsetbox, (xy[0]+w/2.,xy[1]+w/2.),
                    boxcoords="data", pad=0.52,fontsize=linewidth,
                    bboxprops=dict(facecolor = "none", edgecolor='r', 
                              lw = linewidth))
ab.set_zorder(0)
ax.add_artist(ab)

ax.set_xlabel('X Axis', fontsize=16, fontweight='bold')
ax.set_ylabel('Y Axis', fontsize=16, fontweight='bold')

plt.show()

enter image description here

like image 121
ImportanceOfBeingErnest Avatar answered May 30 '26 04:05

ImportanceOfBeingErnest