【问题标题】:How to display print statements interlaced with matplotlib plots inline in Ipython?如何在 Ipython 中显示与 matplotlib 内联图交错的打印语句?
【发布时间】:2015-10-07 14:25:42
【问题描述】:

我希望打印语句的输出与绘图交错,按照它们在 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 中是否有直接的解决方案,或者解决方法或替代解决方案来获得隔行输出?

【问题讨论】:

  • 如果你使用%matplotlib inline,我想你可以调用fig.show()当你想要显示的情节。
  • 已编辑以包含%matplotlib inline。另外在ax.hist(data) 之后调用fig.show() 并没有改变结果。
  • plt.show() 呢?
  • plt.show() 成功了

标签: python matplotlib ipython ipython-notebook


【解决方案1】:

有一个简单的解决方案,绘图后使用 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

此代码将按要求工作

【讨论】:

  • 这应该是默认的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-09
  • 2016-06-22
  • 2013-10-24
  • 1970-01-01
相关资源
最近更新 更多