Matplotlib生成等尺寸多PDF图形的问题求助
How to Ensure Consistent Plot Area Size Across Multiple Matplotlib Figures for LaTeX Insertion
The issue you're facing is that Matplotlib automatically adjusts layout elements like margins based on tick labels, axis titles, and text length—even when using the same figsize. This changes the actual size of your plotting area, making alignment in LaTeX impossible. To fix this, we need to lock the size and position of the plotting axes across all figures, instead of relying on automatic layout adjustments.
Here's how to resolve it step by step:
Key Fixes to Implement
- Disable automatic layout: Turn off
figure.autolayoutso we can manually control margins without Matplotlib overriding them. - Set consistent fixed margins: Use
plt.subplots_adjust()to define identical left/right/bottom/top margins for every figure. This ensures the core plotting area (where your lines are drawn) stays the exact same size. - Standardize label formatting: Keep tick rotation, font size, and formatting consistent across all plots to avoid unexpected layout shifts.
Modified Working Code
Here's your example code updated to enforce perfectly aligned plotting areas:
from matplotlib.lines import Line2D import matplotlib.ticker as mtick import matplotlib.pyplot as plt from matplotlib import rc # Activate LaTeX text rendering rc('text', usetex=True) from matplotlib import rcParams # Disable automatic layout (we'll handle margins manually) rcParams.update({'figure.autolayout': False}) CHUNK_COUNT = 50 common_figsize=(6,5) plot_counter = 5 x_step = int(CHUNK_COUNT / 10) new_xticks = list(range(x_step, CHUNK_COUNT + x_step, x_step)) + [1] # Define FIXED margins for ALL figures (adjust these values if needed) # Values represent fractions of the total figure width/height UNIFORM_MARGINS = { 'left': 0.15, 'right': 0.95, 'bottom': 0.15, 'top': 0.95 } ##### Plot Figure 1 fig, ax = plt.subplots(figsize=common_figsize) plt.ylabel("Summary of a simple YY axis") plt.yticks(rotation=45, fontsize=9) # Consistent font size ax.yaxis.set_major_formatter(mtick.PercentFormatter(is_latex=False)) for i in range(0, plot_counter): xvals = range(1, CHUNK_COUNT + 1) yvals = [j + i for j in xvals] plt.plot(xvals, yvals) plt.xticks(new_xticks) ax.set_xlim(left=1, right=CHUNK_COUNT) # Apply fixed margins to lock plotting area size plt.subplots_adjust(**UNIFORM_MARGINS) plt.savefig("Figure_1.pdf", transparent=True) plt.close(fig) ##### Plot Figure 2 fig, ax = plt.subplots(figsize=common_figsize) plt.ylabel("Summary of another YY axis") plt.yticks(rotation=45, fontsize=9) # Match font size from Figure 1 ax.yaxis.set_major_formatter(mtick.PercentFormatter(is_latex=False)) for i in range(0, plot_counter): xvals = range(1, CHUNK_COUNT + 1) yvals = [(j + i)/100 for j in xvals] plt.plot(xvals, yvals) plt.xticks(new_xticks) ax.set_xlim(left=1, right=CHUNK_COUNT) # Apply the EXACT same margins as Figure 1 plt.subplots_adjust(**UNIFORM_MARGINS) plt.savefig("Figure_2.pdf", transparent=True) plt.close(fig)
Why This Works
- By setting fixed margins with
subplots_adjust(), we reserve a consistent amount of space for labels, ticks, and titles. The remaining area (your actual plotting axes) will have identical dimensions across all figures. - Disabling
figure.autolayoutprevents Matplotlib from overriding our manual layout settings based on variable text lengths.
Additional Tips
- If long LaTeX labels cause overlap, tweak the
leftmargin inUNIFORM_MARGINS(use the same value for all figures) or reduce the font size consistently. - Avoid using
bbox_inches='tight'insavefig()—it will override your fixed margins and reintroduce layout inconsistencies. - For even more precision, you can use
matplotlib.gridspec.GridSpecto define exact axes dimensions, butsubplots_adjust()is simpler for most use cases.
内容的提问来源于stack exchange,提问作者Blitzkoder
相关产品推荐
相关产品推荐

