2017-06-21 234 views
1

我正在嘗試執行以下操作:python matplotlib:在多頁中保存爲pdf

我已經使用matplotlib創建了一個圖,其中包含多個子圖。 更具體地說,2x4子圖

輸出非常適合在屏幕上顯示,但不能將其保存爲pdf。

如果我只是使用save_fig,它將打印一個單頁的pdf文檔,並帶有2x4網格。

我想要做的是重新安排我的子圖,讓我們說一個2x4網格(選擇哪個子圖塊在哪裏,是好的,但不是必需的),並將其打印成2頁的pdf每個子圖。 (爲了能夠適應A4頁面尺寸)

這可能嗎?

謝謝先進!

+1

我想你將不得不將數字'手動'分成兩個並保存到同一個pdf文件。 –

+1

您可以使用'PdfPages'保存多頁PDF:https://matplotlib.org/examples/pylab_examples/multipage_pdf.html但您可能需要創建兩個圖形對象才能做到這一點 – tom

+0

我已經看過多頁樣本代碼,但我想保留當前佈局查看,並創建一個新的佈局保存。我似乎無法找到從原始圖中獲得子圖的方法,並將它們重新排列爲新的子圖。 – GSta

回答

2

我建議創建3個數字。一個用於顯示,另一個用於保存並繪製相同的數據給他們。

import matplotlib.pyplot as plt 
import numpy as np 


data = np.sort(np.cumsum(np.random.rand(24,16), axis=0), axis=0) 

def plot(ax, x, y, **kwargs): 
    ax.plot(x,y, **kwargs) 

colors = ["crimson", "indigo", "limegreen", "gold"] 
markers = ["o", "", "s", ""] 
lines = ["", "-", "", ":"] 

# figure 0 for showing 
fig0, axes = plt.subplots(nrows=2,ncols=4) 

for i, ax in enumerate(axes.flatten()): 
    plot(ax, data[:,2*i], data[:,2*i+1], marker=markers[i%4], ls=lines[i%4],color=colors[i%4]) 


# figure 1 for saving 
fig1, axes = plt.subplots(nrows=1,ncols=4) 
for i, ax in enumerate(axes.flatten()): 
    plot(ax, data[:,2*i], data[:,2*i+1], marker=markers[i], ls=lines[i],color=colors[i]) 

#figure 2 for saving 
fig2, axes = plt.subplots(nrows=1,ncols=4) 
for i, ax in enumerate(axes.flatten()): 
    plot(ax, data[:,2*i+4], data[:,2*i+1+4], marker=markers[i], ls=lines[i],color=colors[i]) 

#save figures 1 and 2 
fig1.savefig(__file__+"1.pdf") 
fig2.savefig(__file__+"2.pdf") 

#close figures 1 and 2 
plt.close(fig1) 
plt.close(fig2) 
#only show figure 0 
plt.show() 
1

由於我在工作中需要類似的東西,所以我根據顯示介質自動化了將圖形分組爲圖形的過程。起初,我的想法是隻做一次每個情節,只是將小圖添加到數字中以保存在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_colmax_row關鍵字,然後創建數字與副區的根據量。然後循環遍歷給定的函數列表,並將其繪製在每個函數的子圖上。未使用的子圖被刪除。最後返回所有數字的列表。

在我的例子中,我有9種不同的功能,我首先在屏幕上以2x3佈局顯示(總共有兩個數字,一個帶有6個子圖,另一個帶有3個子圖)。如果用戶很滿意,則以2×4佈局(也是兩個數字,但這次是一個包含8個子圖,1個包含1個子圖)重新繪製圖,然後保存到multipage_pdf.pdf之後的example in the documentation之後的文件中。

python 3.5測試