2017-08-24 42 views
0

我希望我在正確的地方提出這個問題。在一個圖中繪製一些東西,稍後再用它來繪製另一個圖

我有一個for循環,其中創建了許多數字。 循環結束後,我想再生成一個更多的圖,其中三個以前創建的圖作爲插圖。

我的代碼現在的問題是這樣的:

import numpy as np 
import matplotlib.pyplot as plt 

def f(t): 
    return np.exp(-t)*np.cos(2*np.pi*t)+(t/10)**2. 

t1=np.arange(0.0,5.0,0.1) 
t2=np.arange(0.0,5.0,0.02) 


for i in range(2): 
    fig= plt.figure(i) 
    ax1=fig.add_subplot(111) 
    plt.title('Jon Snow') 
    kraft_plot,=ax1.plot(t1,np.sin(t1),color='purple') 
    tyrion=ax1.axvline(2,color='darkgreen',ls='dashed') 
    ax1.set_ylabel('Kraft [N]',color='purple',fontweight='bold') 
    ax1.set_xlabel('Zeit [s]',fontweight='bold') 
    ax2=ax1.twinx() 
    strecke_plot,=ax2.plot(t2,t2/5,color='grey',label='Verlauf der Strecke') 
    ax2.set_ylabel('Strecke [mm]',color='grey',fontweight='bold') 
    ax1.legend((kraft_plot,tyrion,strecke_plot),('Jonny','Dwarf','andalltherest'),loc=2) 

plt.show() 

你能幫助我嗎?我可以保存整個圖形/情節?

乾杯,Dalleaux。

編輯:這應該是這樣的(右邊是我想達到的目標): The text in the right should be normal sclaed, obviously...

的問題是,我首先要具備單獨printet的數字,然後一起(最後我想保存爲帶有三位數字的pdf/png)

+0

你的問題是在正確的地方,是的。然而,目前還不清楚你到底想要達到什麼目的。可能這僅僅是由於你所謂的「三個早期創建的地塊」的意思。你的定義是什麼「情節」?就我所見,上面的代碼創建了2個數字。每個圖有2個子圖。因此,你最終總共有4個地塊。是否你想用這些新圖中的3個地塊?如果是這樣,你想如何選擇你使用哪一個? – ImportanceOfBeingErnest

+0

你好@ImportanceOfBeingErnest, 那麼,我從這段代碼中得到2個數字,其中有一個視圖。 之後,我想有第三個數字,其中兩個起源數字合併(一個在另一個之上)。 – dalleaux

回答

1

在matplotlib中,座標軸(子圖)總是隻有一個圖的一部分。雖然有options to copy an axes from one figure to another,但這是一個相當複雜的過程。相反,您可以簡單地重新創建情節,只需幾個數字即可。使用一個將座標軸繪製爲參數的函數,使得這個過程非常簡單。

爲了將所有三個數字保存爲PDF格式,您可以使用pdfPages,如代碼底部所示。

import numpy as np 
import matplotlib.pyplot as plt 

def f(t): 
    return np.exp(-t)*np.cos(2*np.pi*t)+(t/10)**2. 

t1=np.arange(0.0,5.0,0.1) 
t2=np.arange(0.0,5.0,0.02) 

def plot(ax, i): 
    ax.set_title('Jon Snow') 
    kraft_plot,=ax.plot(t1,np.sin(t1),color='purple') 
    tyrion=ax.axvline(2,color='darkgreen',ls='dashed') 
    ax.set_ylabel('Kraft [N]',color='purple',fontweight='bold') 
    ax.set_xlabel('Zeit [s]',fontweight='bold') 
    ax2=ax.twinx() 
    strecke_plot,=ax2.plot(t2,t2/5,color='grey',label='Verlauf der Strecke') 
    ax2.set_ylabel('Strecke [mm]',color='grey',fontweight='bold') 
    ax.legend((kraft_plot,tyrion,strecke_plot),('Jonny','Dwarf','andalltherest'),loc=2) 

figures=[] 

for i in range(2): 
    fig= plt.figure(i) 
    ax1=fig.add_subplot(111) 
    plot(ax1, i) 
    figures.append(fig) 

# create third figure 
fig, (ax1,ax2) = plt.subplots(nrows=2) 
plot(ax1, 0) 
plot(ax2, 1) 
figures.append(fig) 

from matplotlib.backends.backend_pdf import PdfPages 
with PdfPages('multipage_pdf.pdf') as pdf: 
    for fig in figures: 
     pdf.savefig(fig) 


plt.show() 

三頁的PDF輸出:

enter image description here

+0

非常感謝。我得到它的工作,即使它需要一點點工作,因爲我的原始代碼稍微複雜一些;) – dalleaux

相關問題