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

Syd*_*Syd 6 python plot matplotlib

我有一个使用matplotlib生成图形的Python程序。我试图让该程序在一个程序运行中生成一堆图(询问用户是否要生成另一个图),所有这些都在单独的窗口中进行。有什么办法可以做到吗?

use*_*323 10

使用最新的 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()
Run Code Online (Sandbox Code Playgroud)


小智 9

要生成新图形,可以在程序执行任何绘图之前添加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)
Run Code Online (Sandbox Code Playgroud)


Wil*_*lle 0

使用.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()
Run Code Online (Sandbox Code Playgroud)

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

  • `plt.figure` 是一个函数而不是方法,并且总是创建一个新窗口,`plt.gcf()` 使用当前窗口。 (2认同)