2015-05-06 32 views
1

我知道有多種方法可以在一個圖中繪製多個圖形。一種這樣的方式是使用軸,例如,如何繪製小圖中的圖形(Matplotlib)

import matplotlib.pyplot as plt 
fig, ax = plt.subplots() 
ax.plot([range(8)]) 
ax.plot(...) 

因爲我有我的美化圖表和隨後返回一個數字的功能,我想用這個數字在我的次要情節來繪製。它應該看起來類似於此:

import matplotlib.pyplot as plt 
fig, ax = plt.subplots() 
ax.plot(figure1) # where figure is a plt.figure object 
ax.plot(figure2) 

這不起作用,但我怎麼能使它工作?有沒有辦法將數字放在子圖或者解決方法中,在一個整體數字中繪製多個數字?

任何幫助,這是非常感謝。 在此先感謝您的意見。

回答

1

一種可能的解決方案是

import matplotlib.pyplot as plt 

# Create two subplots horizontally aligned (one row, two columns) 
fig, ax = plt.subplots(1,2) 
# Note that ax is now an array consisting of the individual axis 

ax[0].plot(data1) 
ax[1].plot(data2) 

然而,爲了工作data1,2需要是數據。如果你有一個已經爲你繪製數據的函數,我建議在你的函數中包含axis參數。例如

def my_plot(data,ax=None): 
    if ax == None: 
     # your previous code 
    else: 
     # your modified code which plots directly to the axis 
     # for example: ax.plot(data) 

然後你就可以繪製它像

import matplotlib.pyplot as plt 

# Create two subplots horizontally aligned 
fig, ax = plt.subplots(2) 
# Note that ax is now an array consisting of the individual axis 

my_plot(data1,ax=ax[0]) 
my_plot(data2,ax=ax[1]) 
+0

非常感謝您的回答,但這正是我想要規避的。我不想繪製數據,而是一個容易檢索的圖形對象。 – Arne

+1

@Arne:我從來沒有見過內置函數,其中包含兩個數字成一個單一的數字。因此,有必要從數字對象中提取所有數據,並使用多個座標軸在新圖中再次繪製它們。儘管這可能是可能的,但比簡單地將軸作爲參數更復雜。 – plonser

1

如果目標僅僅是定製個人次要情節,爲什麼不改變你的函數動態更改目前的數字,而不是返回一個數字。從matplotlibseaborn,你可以改變繪圖時的繪圖設置嗎?

import numpy as np 
import matplotlib.pyplot as plt 

plt.figure() 

x1 = np.linspace(0.0, 5.0) 
x2 = np.linspace(0.0, 2.0) 

y1 = np.cos(2 * np.pi * x1) * np.exp(-x1) 
y2 = np.cos(2 * np.pi * x2) 

plt.subplot(2, 1, 1) 
plt.plot(x1, y1, 'ko-') 
plt.title('A tale of 2 subplots') 
plt.ylabel('Damped oscillation') 

import seaborn as sns 

plt.subplot(2, 1, 2) 
plt.plot(x2, y2, 'r.-') 
plt.xlabel('time (s)') 
plt.ylabel('Undamped') 

plt.show() 

enter image description here

也許我並不完全明白你的問題。這個「美化」功能是否複雜?...

相關問題