Matplotlib技术问题:如何在绘图左侧添加1英寸空白边距?
解决Matplotlib A4绘图左侧留1英寸打孔空白的方案
我来给你几个实用的办法,轻松搞定Matplotlib生成A4 PDF时的左侧打孔空白问题,每一种都能精准留出1英寸的空间:
方法1:手动调整子图边距(最简单直接)
这个方法直接在创建Figure后,调整子图区域的左侧边距,计算方式是用1英寸除以A4页面的宽度(8.27英寸),得到相对比例后设置给subplots_adjust:
import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages # 创建A4尺寸的Figure(单位:英寸) fig = plt.figure(figsize=(8.27, 11.69)) # A4标准尺寸:210mm×297mm = 8.27×11.69英寸 # 设置左侧1英寸空白:计算相对比例(1英寸 / 页面宽度) left_margin_inch = 1.0 fig.subplots_adjust(left=left_margin_inch / fig.get_figwidth()) # 添加3个垂直排列的子图 ax1 = fig.add_subplot(3, 1, 1) ax1.plot([1, 2, 3], [4, 5, 6]) ax1.set_title('Plot 1') ax2 = fig.add_subplot(3, 1, 2) ax2.plot([1, 2, 3], [6, 5, 4]) ax2.set_title('Plot 2') ax3 = fig.add_subplot(3, 1, 3) ax3.plot([1, 2, 3], [5, 5, 5]) ax3.set_title('Plot 3') # 保存为PDF(注意不要用bbox_inches='tight',会覆盖手动设置的边距) with PdfPages('a4_plots_with_margin.pdf') as pdf: pdf.savefig(fig) plt.close(fig)
方法2:用GridSpec精确控制布局(适合复杂子图)
如果你的子图布局更复杂,用GridSpec可以更精细地控制每个子图的位置,直接指定左侧空白的绝对尺寸:
import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec from matplotlib.backends.backend_pdf import PdfPages fig = plt.figure(figsize=(8.27, 11.69)) left_margin_inch = 1.0 # 计算可用区域的宽度:页面宽度 - 左侧空白 available_width = fig.get_figwidth() - left_margin_inch # 创建GridSpec,设置左偏移为1英寸(用比例:left_margin / 页面宽度) gs = GridSpec(3, 1, left=left_margin_inch / fig.get_figwidth(), width_ratios=[available_width]) # 逐个添加子图 ax1 = fig.add_subplot(gs[0]) ax1.plot([1,2,3], [4,5,6]) ax1.set_title('Plot 1') ax2 = fig.add_subplot(gs[1]) ax2.plot([1,2,3], [6,5,4]) ax2.set_title('Plot 2') ax3 = fig.add_subplot(gs[2]) ax3.plot([1,2,3], [5,5,5]) ax3.set_title('Plot 3') # 保存PDF with PdfPages('a4_plots_gridspec.pdf') as pdf: pdf.savefig(fig) plt.close(fig)
方法3:全局设置默认边距(批量生成图时用)
如果你要生成多个带左侧空白的A4图,可以直接修改Matplotlib的全局配置,一劳永逸:
import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages # 全局设置A4页面的左侧边距为1英寸对应的比例 plt.rcParams['figure.figsize'] = (8.27, 11.69) # 默认A4尺寸 plt.rcParams['figure.subplot.left'] = 1.0 / 8.27 # 1英寸左边距的相对比例 # 接下来创建的所有Figure都会自动应用这个边距 fig = plt.figure() ax1 = fig.add_subplot(3,1,1) ax1.plot([1,2,3], [4,5,6]) ax1.set_title('Plot 1') # 省略其他子图代码... with PdfPages('batch_plots.pdf') as pdf: pdf.savefig(fig) plt.close(fig)
注意事项
- 保存PDF时不要添加
bbox_inches='tight'参数,这个参数会自动压缩边距,覆盖你手动设置的空白。 - A4尺寸的转换要准确:210mm=8.27英寸,297mm=11.69英寸,用英寸作为单位更符合Matplotlib的默认设置。
- 如果你需要同时调整其他边距(比如上下右),可以在
subplots_adjust里添加right、top、bottom参数,同样用相对比例设置。
内容的提问来源于stack exchange,提问作者Steve Maughan
相关产品推荐
相关产品推荐

