Matplotlib如何为不同图表y轴刻度标签设置统一间距保证左脊线位置一致
问题原因
你遇到的坐标轴左脊线偏移问题来自两个核心原因:
- 保存图片时使用的
bbox_inches="tight"参数会动态调整坐标轴位置和画布裁剪范围,自动适配y轴标签的宽度,当标签从两位变为三位时,坐标轴会整体向右偏移,导致左脊线位置变化,你之前手动计算的left_margin参数也会被该设置覆盖。 - 默认字体不是等宽字体,即使用
%3d格式化了三位整数,空格和数字的渲染宽度也不一致,会带来微小的间距差异。
解决方案
按以下步骤修改代码即可完全固定左脊线位置:
- 移除
savefig中的bbox_inches="tight"参数,保留手动设置的坐标轴位置,保证所有图的坐标轴坐标完全统一。 - 将y轴刻度的字体设置为等宽字体,保证三位占位的宽度完全一致。
修改后的完整代码
from matplotlib import pyplot as plt from matplotlib.ticker import FormatStrFormatter from matplotlib.ticker import MaxNLocator import numpy as np import os def plot_figure(start, end, figure_name): fwidth = 15 fheight = 7 fig = plt.figure(figsize=(fwidth, fheight), facecolor=None) plt.style.use('ggplot') # define margins left_margin = 0.95 / fwidth right_margin = 0.2 / fwidth bottom_margin = 0.5 / fheight top_margin = 0.25 / fheight # create axes x = left_margin # 坐标轴左下角水平坐标 y = bottom_margin # 坐标轴左下角垂直坐标 w = 1 - (left_margin + right_margin) # 坐标轴宽度 h = 1 - (bottom_margin + top_margin) # 坐标轴高度 ax = fig.add_axes([x, y, w, h]) ax.set_facecolor('white') # 设置坐标轴边框样式 for edge_i in ['left', 'bottom','right', 'top']: ax.spines[edge_i].set_edgecolor("black") ax.spines[edge_i].set_linewidth(3) plus_minus = 50 x = np.arange(-plus_minus, plus_minus + 1, 1) signal_array = np.random.randint(start, end + 1, size = 2*plus_minus+1) plt.plot(x, signal_array, color='b', label='Signal', linewidth=2, zorder=10) # 设置刻度样式 plt.tick_params(axis='both', which='major', labelsize=50, width=3, length=10) plt.tick_params(axis='both', which='minor', labelsize=50, width=3, length=10) # 设置x轴刻度和范围 plt.xticks(np.arange(-plus_minus/2, plus_minus/2+1, step=plus_minus/2), fontsize=50) plt.xlim((-plus_minus, plus_minus)) # y轴设置:三位整数格式化 + 等宽字体保证占位宽度一致 ax.yaxis.set_major_formatter(FormatStrFormatter('%3d')) ax.yaxis.set_major_locator(MaxNLocator(integer=True, min_n_ticks=3, nbins=2)) ax.yaxis.set_major_locator(MaxNLocator(3)) # 设置y轴刻度为等宽字体 ax.set_yticklabels(ax.get_yticks(), fontfamily='monospace') figure_file = os.path.join('/Users','burcakotlu','Desktop',f'{figure_name}.png') # 移除bbox_inches参数,保留手动设置的固定布局 fig.savefig(figure_file, dpi=100) plt.close(fig) plot_figure(20, 50, 'test1') plot_figure(100, 130, 'test2')
可选补充
如果你确实需要自动裁剪多余白边,可以保留bbox_inches="tight",同时添加以下代码固定左侧边距:
fig.subplots_adjust(left=0.15) # 固定左侧边距为0.15,可根据需要调整数值
此时matplotlib会在固定左侧边距的基础上裁剪其他方向的白边,也能保证左脊线位置一致。
内容的提问来源于stack exchange,提问作者burcak
相关产品推荐
相关产品推荐

