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

问题描述 投票:0回答:2

我对增加 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')
python matplotlib plot axis-labels yaxis
2个回答
2
投票

具有相同效果的一个选项是创建一个与轴范围完全相同的白色矩形,这样轴内的脊柱部分就被矩形隐藏了。这将需要将线宽设置为两倍,因为只能看到一半的线。

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

我在这里将刺设为黄色,这样它们就不会隐藏蜱虫和蜱虫标签。

另一种选择是适应 Set matplotlib矩形边缘到指定宽度之外?的答案,以创建一个严格包围绘图中的区域的矩形,如下所示:

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


0
投票

可以在 Spine

 对象上使用 
set_position((position type, amount)) 方法来实现此目的,并将 position type 设置为“向外”,并将 amount 设置为轴所需厚度的一半。这样,轴就已经远离绘图域,足以适应它们的厚度。

因此,在您的示例中,需要添加以下行:

for axis in ['top','bottom','left','right']:
  ax.spines[axis].set_linewidth(30)
  ax.spines[axis].set_position(("outward", 15))
© www.soinside.com 2019 - 2024. All rights reserved.