如何在Ipython中显示与matplotlib图交织的打印语句?

时间:2015-07-17 19:09:01

标签: python matplotlib ipython ipython-notebook

我希望打印语句的输出与绘图交错,按照打印顺序在Ipython笔记本单元格中绘制。例如,请考虑以下代码:

(使用ipython notebook --no-browser --no-mathjax启动ipython)

%matplotlib inline
import matplotlib.pyplot as plt

i = 0
for data in manydata:
    fig, ax = plt.subplots()
    print "data number i =", i
    ax.hist(data)
    i = i + 1

理想情况下,输出看起来像:

data number i = 0
(histogram plot)
data number i = 1
(histogram plot)
...

然而,Ipython中的实际输出将如下所示:

data number i = 0
data number i = 1
...
(histogram plot)
(histogram plot)
...

Ipython中有直接的解决方案,还是解决方案或替代解决方案来获得隔行输出?

1 个答案:

答案 0 :(得分:16)

有简单的解决方案,在绘图后使用matplotlib.pyplot.show()函数。

这将在执行代码的下一行

之前显示图形
%matplotlib inline
import matplotlib.pyplot as plt

i = 0
for data in manydata:
    fig, ax = plt.subplots()
    print "data number i =", i
    ax.hist(data)
    plt.show() # this will load image to console before executing next line of code
    i = i + 1

此代码将按要求运行