由於我在工作中需要類似的東西,所以我根據顯示介質自動化了將圖形分組爲圖形的過程。起初,我的想法是隻做一次每個情節,只是將小圖添加到數字中以保存在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