如何用Pandas结合Matplotlib制作2x2子图并通过Pdfpages存为单页PDF
问题
我目前用Python的PdfPages工具,原本是通过Pandas DataFrame分别绘制4个图表,每个图表单独存为PDF的一页,代码如下:
df1.plot(x='col1', y=['col2', 'col3'], style='-', title=title1) pdf.savefig() plt.close() df2.plot(x='col1', y=['col2', 'col3'], style='-', title=title2) pdf.savefig() plt.close() df3.plot(x='col1', y=['col2', 'col3'], style='-', title=title3) pdf.savefig() plt.close() df4.plot(x='col1', y=['col2', 'col3'], style='-', title=title4) pdf.savefig() plt.close()
我知道Matplotlib可以通过子图函数创建2x2布局的多图,示例代码如下:
# Initialise the subplot function using number of rows and columns figure, axis = plt.subplots(2, 2) # For Sine Function axis[0, 0].plot(X, Y1) axis[0, 0].set_title("Sine Function") # For Cosine Function axis[0, 1].plot(X, Y2) axis[0, 1].set_title("Cosine Function") ... etc # Then use pdfpages, e.g. pdf.savefig(figure)
现在想把df1到df4的图表整合为2x2布局的单页图表,再保存到PDF的同一页,该怎么实现?
解决方案
直接利用Matplotlib的subplots创建2x2子图布局,然后指定每个DataFrame的绘图目标为对应的子图轴对象即可,完整代码如下:
import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages import pandas as pd # 假设df1-df4、title1-title4已提前定义好 # 创建2x2的子图布局,可根据需求调整画布大小 fig, axes = plt.subplots(2, 2, figsize=(12, 8)) # 在对应子图上绘制DataFrame图表 df1.plot(x='col1', y=['col2', 'col3'], style='-', title=title1, ax=axes[0, 0]) df2.plot(x='col1', y=['col2', 'col3'], style='-', title=title2, ax=axes[0, 1]) df3.plot(x='col1', y=['col2', 'col3'], style='-', title=title3, ax=axes[1, 0]) df4.plot(x='col1', y=['col2', 'col3'], style='-', title=title4, ax=axes[1, 1]) # 自动调整子图间距,避免标题、标签重叠 plt.tight_layout() # 将整个布局保存到PDF的同一页 with PdfPages('combined_plots.pdf') as pdf: pdf.savefig(fig) plt.close(fig)
关键说明
plt.subplots(2,2)会生成一个包含4个子图的画布,axes是2x2的数组,对应每个子图的轴对象。- Pandas的
plot方法支持通过ax参数指定绘图目标,把每个DataFrame的图表精准绘制到对应子图位置。 plt.tight_layout()自动优化子图间距和尺寸,解决元素重叠问题,提升图表可读性。- 最后将整个
fig对象保存到PDF,就能实现4个图表在同一页的2x2布局。
内容的提问来源于stack exchange,提问作者JDS
相关产品推荐
相关产品推荐

