Skip to main content
 首页 » 编程设计

python之增加 Matplotlib 中的轴粗度(不切入绘图域!)

2024年12月31日9telwanggs

我对在 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') 

请您参考如下方法:

具有相同效果的一个选项是创建一个完全具有轴范围的白色矩形,这样位于轴内的书脊部分被矩形隐藏。这将需要使线宽加倍,因为只能看到一半的线。

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