matplotlib:在新窗口中生成新图形以供后续程序运行

2024-04-23 16:43:49 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

使用最新的matlibplot,我发现以下内容适合我的目的:

# create figure (will only create new window if needed)
plt.figure()
# Generate plot1
plt.plot(range(10, 20))
# Show the plot in non-blocking mode
plt.show(block=False)

# create figure (will only create new window if needed)
plt.figure()
# Generate plot2
plt.plot(range(10, 20))
# Show the plot in non-blocking mode
plt.show(block=False)

...

# Finally block main thread until all plots are closed
plt.show()

要生成新的图形,可以在程序进行任何绘图之前添加plt.figure()。

import matplotlib.pyplot as plt
import numpy as np

def make_plot(slope):
    x = np.arange(1,10)
    y = slope*x+3
    plt.figure()
    plt.plot(x,y)

make_plot(2)
make_plot(3)

确保所有线条都进入正确的体形窗口的最简单方法如下:

from six.moves import input
import matplotlib.pyplot as plt
another = True
while another:
    fig, ax = plt.subplots()

    ax.plot(range(5))


    fig.canvas.manager.show() 
    # this makes sure that the gui window gets shown
    # if this is needed depends on rcparams, this is just to be safe
    fig.canvas.flush_events() 
    # this make sure that if the event loop integration is not 
    # set up by the gui framework the plot will update

    another = bool(input("would you like another? "))

如果要在非gui后端运行此命令,则需要放弃flush_events调用或将其包装在try: ... except NotImplementedError中。这种复杂性的大部分是防御性编程,因为gui可能很难实现,并且此代码的行为可能依赖于许多从所示代码中看不到的因素。

使用pyplot的隐式轴可能会导致问题,因为“当前轴”是由用户单击的最后一个轴设置的。在rpel上交互输入时,您应该只使用pyplot,而在脚本/程序中几乎不使用(除了plt.subplots)。

相关问题 更多 >