增加Matplotlib中的轴厚度(无需切入图域!)

时间:2018-10-08 19:18:46

标签: python matplotlib plot axis-labels yaxis

我对增加matplotlib中轴的厚度(不切入图的范围)感兴趣。也就是说,我希望轴的厚度从图上向外延伸,而不是向内延伸。这样的事情有可能吗?

传统方法(例如,参见下文)似乎无效:

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')

1 个答案:

答案 0 :(得分:0)

具有相同效果的一个选项是创建一个完全具有轴范围的白色矩形,这样,轴内部的棘刺部分将被矩形隐藏。然后,这将需要使线宽增大两倍,因为只能看到一半的线。

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()

我在这里使脊椎发黄,这样它们就不会隐藏壁虱和壁虱标签。

enter image description here

另一种选择是改编Set matplotlib rectangle edge to outside of specified width?中的答案,以创建一个矩形,该矩形严格将图中的区域封闭起来,如下所示:

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