2015-04-09 8 views
17

Si consideri il seguente codice in esecuzione in ipython/Jupyter Notebook:iPython/Jupyter Notebook and Pandas, come tracciare più grafici in un ciclo for?

from pandas import * 
%matplotlib inline 

ys = [[0,1,2,3,4],[4,3,2,1,0]] 
x_ax = [0,1,2,3,4] 

for y_ax in ys: 
    ts = Series(y_ax,index=x_ax) 
    ts.plot(kind='bar', figsize=(15,5)) 

mi sarei aspettato di avere 2 lotti separati come output, invece ho ricevuto le due serie fuse in un'unica trama. Perché è quello? Come posso ottenere due grafici separati mantenendo il ciclo for?

risposta

22

Basta aggiungere la chiamata a plt.show() dopo si traccia il grafico (si potrebbe desiderare di import matplotlib.pyplot per farlo), in questo modo:

from pandas import * 
import matplotlib.pyplot as plt 
%matplotlib inline 

ys = [[0,1,2,3,4],[4,3,2,1,0]] 
x_ax = [0,1,2,3,4] 

for y_ax in ys: 
    ts = Series(y_ax,index=x_ax) 
    ts.plot(kind='bar', figsize=(15,5)) 
    plt.show() 
+0

Grande! Facile peacy. Grazie @ Andrea Sobolev –

12

Nel notebook IPython il modo migliore per farlo è spesso con sottotrame . Si creano più assi sulla stessa figura e quindi si esegue il rendering della figura nel blocco note. Per esempio:

import pandas as pd 
import matplotlib.pyplot as plt 

%matplotlib inline 

ys = [[0,1,2,3,4],[4,3,2,1,0]] 
x_ax = [0,1,2,3,4] 

fig, axs = plt.subplots(ncols=2, figsize=(10, 4)) 
for i, y_ax in enumerate(ys): 
    pd.Series(y_ax, index=x_ax).plot(kind='bar', ax=axs[i]) 
    axs[i].set_title('Plot number {}'.format(i+1)) 

genera le seguenti classifiche

enter image description here