41

考虑在 iPython/Jupyter Notebook 中运行的以下代码:

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))

我希望有 2 个单独的图作为输出,相反,我将两个系列合并到一个图中。这是为什么?如何获得两个单独的图来保持for循环?

4

2 回答 2

56

只需在绘制图表后添加调用plt.show()(您可能想import matplotlib.pyplot要这样做),如下所示:

from pandas import Series
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()
于 2015-04-09T08:27:56.210 回答
30

在 IPython 笔记本中,最好的方法通常是使用子图。您在同一个图形上创建多个轴,然后在笔记本中渲染该图形。例如:

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))

生成以下图表

在此处输入图像描述

于 2015-04-09T08:38:12.910 回答