matplotlib:在新窗口中生成一个新图形,用于后续程序运行

时间:2015-07-28 20:33:34

标签: python matplotlib plot

我有一个使用matplotlib生成图形的Python程序。我试图让程序在一个程序运行中生成一堆图(用户被问到是否要生成另一个图),所有这些都在不同的窗口中。我能以任何方式做到这一点吗?

4 个答案:

答案 0 :(得分:6)

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

handle_cast(waitConnection, State = #state{listenSocket = ListenSocket}) ->
    io:format("ListenSocket ok ~n"),
    {ok,Socket} = gen_tcp:accept(ListenSocket),
    io:format("cast wait accept ~n"),
    Pid = spawn(?MODULE,get_request,[Socket,[]]),
    gen_tcp:controlling_process(Socket,Pid),
    waitConnection(),
    {noreply, State}.

答案 1 :(得分:2)

使用最新的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()

答案 2 :(得分:1)

确保所有线路进入正确数字窗口的最简单方法是:

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除外)。

答案 3 :(得分:-2)

使用.figure()功能创建一个新窗口,以下代码生成两个窗口:

import matplotlib.pyplot as plt

plt.plot(range(10))  # Creates the plot.  No need to save the current figure.
plt.draw()  # Draws, but does not block

plt.figure()  # New window, if needed.  No need to save it, as pyplot uses the concept of current figure
plt.plot(range(10, 20))
plt.draw()

您可以根据需要多次重复此操作