由于我在工作中需要类似的东西,所以我根据显示介质自动化了将图形分组为图形的过程。起初,我的想法是只做一次每个情节,只是将小图添加到数字中以保存在PDF中,但遗憾的是,根据this answer中的评论,这是不可能的,因此所有事情都需要重新绘制。代码示出了如何这可以使用PdfPages
被自动化的总体思路:
from matplotlib import pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
def niter(iterable, n):
"""
Function that returns an n-element iterator, i.e.
sub-lists of a list that are max. n elements long.
"""
pos = 0
while pos < len(iterable):
yield iterable[pos:pos+n]
pos += n
def plot_funcs(x, functions, funcnames, max_col, max_row):
"""
Function that plots all given functions over the given x-range,
max_col*max_row at a time, creating all needed figures while doing
so.
"""
##amount of functions to put in one plot
N = max_col*max_row
##created figures go here
figs = []
##plotted-on axes go here
used_axes = []
##looping through functions N at a time:
for funcs, names in zip(niter(functions, N), niter(funcnames,N)):
##figure and subplots
fig, axes = plt.subplots(max_col, max_row)
##plotting functions
for name,func,ax in zip(names, funcs, axes.reshape(-1)):
ax.plot(x, func(x))
ax.set_title(name)
used_axes.append(ax)
##removing empty axes:
for ax in axes.reshape(-1):
if ax not in used_axes:
ax.remove()
fig.tight_layout()
figs.append(fig)
return figs
##some functions to display
functions = [
lambda x: x, lambda x: 1-x, lambda x: x*x, lambda x: 1/x, #4
np.exp, np.sqrt, np.log, np.sin, np.cos, #5
]
funcnames = ['x','1-x', 'x$^2$', '1/x', 'exp', 'sqrt', 'log', 'sin','cos']
##layout for display on the screen
disp_max_col = 3
disp_max_row = 2
##layout for pdf
pdf_max_col = 2
pdf_max_row = 4
##displaying on the screen:
x = np.linspace(0,1,100)
figs = plot_funcs(x, functions, funcnames, disp_max_row, disp_max_col)
plt.show()
##saving to pdf if user wants to:
answer = input('Do you want to save the figures to pdf?')
if answer in ('y', 'Y', 'yes', ''):
##change number of subplots
N = disp_max_col*disp_max_row
figs = plot_funcs(x, functions, funcnames, pdf_max_row, pdf_max_col)
##from https://matplotlib.org/examples/pylab_examples/multipage_pdf.html
with PdfPages('multipage_pdf.pdf') as pdf:
for fig in figs:
plt.figure(fig.number)
pdf.savefig()
的核心功能,plot_funcs
需要max_col
和max_row
关键字,然后创建数字与副区的根据量。然后循环遍历给定的函数列表,并将其绘制在每个函数的子图上。未使用的子图被删除。最后返回所有数字的列表。
在我的例子中,我有9种不同的功能,我首先在屏幕上以2x3布局显示(总共有两个数字,一个带有6个子图,另一个带有3个子图)。如果用户很满意,则以2×4布局(也是两个数字,但这次是一个包含8个子图,1个包含1个子图)重新绘制图,然后保存到multipage_pdf.pdf
之后的example in the documentation之后的文件中。
python 3.5测试
我想你将不得不将数字'手动'分成两个并保存到同一个pdf文件。 –
您可以使用'PdfPages'保存多页PDF:https://matplotlib.org/examples/pylab_examples/multipage_pdf.html但您可能需要创建两个图形对象才能做到这一点 – tom
我已经看过多页样本代码,但我想保留当前布局查看,并创建一个新的布局保存。我似乎无法找到从原始图中获得子图的方法,并将它们重新排列为新的子图。 – GSta