使用图柄指定在matplotlib图中jupyter中呈现图的位置 [英] Specify where in output matplotlib figures are rendered in jupyter using figure handles

查看:665
本文介绍了使用图柄指定在matplotlib图中jupyter中呈现图的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用matplotlib时,对我而言,常见的模式是将一个函数加到函数中,将其返回,然后让调用者决定如何处理它(渲染到屏幕,保存到文件等).

When working with matplotlib, a common pattern for me is to figure in a function, return it, and let the caller decide what t do with it (render to screen, save to file etc...).

在jupyter笔记本中,我想循环调用这样的函数,并确保图形输出是有序的.在 https://stackoverflow.com/a/53450873/4050510 的答案中,我们了解到plt.show()可以为我们提供帮助与放纵的图像.该答案的重写为:

In jupyter notebook, I want to call such a function in a loop, and make sure that figure output is in order. In this answer https://stackoverflow.com/a/53450873/4050510 , we learn that plt.show() can help us with randering images. A rewrite of that answer is:

# cell 1
%matplotlib inline
import matplotlib.pyplot as plt
def make_figure(i):
    f = plt.figure(i)
    plt.plot([1,i,3])
    return f

#cell 2
for i in range(3):
    f = make_figure(i)
    print(i)
    plt.show()

上面的代码确实有效.问题是,如果我要先创建所有图形,然后按选定的顺序渲染它们,则解决方案将失效. plt.show()将同时渲染所有打开的图形.

The code above indeed works. The problem is that the solution breaks down if I want to create all the figures first, and then render them in chosen order. plt.show() will render all open figures at the same time.

#cell 3
fs = [(i,make_figure(i)) for i in range(3)]
for i,f in fs:
    print(i)
    plt.show()

要进行的自然修改是将plt.show()更改为f.show().在jupyter笔记本之外,可以很好地解决该问题.

The natural modification to make is to change the plt.show() into f.show(). Outside of jupyter notebook, that would solve the problem well.

# cell 4
fs = [(i,make_figure(i)) for i in range(3)]
for i,f in fs:
    print(i)
    f.show()

这不起作用,引发UserWarning: Matplotlib is currently using module://ipykernel.pylab.backend_inline, which is a non-GUI backend, so cannot show the figure.

这种行为差异的解释是什么?给定一组图柄,如何按选定的顺序渲染matplotlib图?

What is the explanation for this difference in behavior? How can I render matplotlib figures in chosen order, given a set of figure handles?

推荐答案

figure.show()仅可用于已运行事件循环的交互式后端.

figure.show() can only be used in interactive backends with an event loop already running.

在具有inline后端的jupyter笔记本中,没有事件循环. 但是,类似于 Matplotlib-使用plt.imshow()时序列关闭此答案,您可以执行后端也可以执行的操作,即调用display(figure).

In jupyter notebook with the inline backend, you have no event loop. However, similar to Matplotlib - sequence is off when using plt.imshow() and and this answer you can instead just do what the backend would also do, namely call display(figure).

单元格1

%matplotlib inline
import matplotlib.pyplot as plt
from IPython.display import display

def make_figure(i):
    f = plt.figure(i)
    plt.plot([1,i,3])
    return f

单元2

%%capture

fs = [(i,make_figure(i)) for i in range(3)]

单元3

for i, f in fs[::-1]:
    display(f)

这篇关于使用图柄指定在matplotlib图中jupyter中呈现图的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆