python中不阻塞执行的图形绘制

2024-04-20 06:06:10 发布

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

我想在while循环中绘制图形,但在表演(G) 命令,并在手动关闭绘图窗口时继续。在

代码:

while True:    
        print G.edges()
        Q = #coming from a function
        if Q > BestQ:
            nx.draw(G)
            plt.show(G)
        if G.number_of_edges() == 0:
            break

这是G.edges()两次迭代的输出:

^{pr2}$

如何使这继续后策划???在


Tags: 代码from命令true图形绘图if绘制
1条回答
网友
1楼 · 发布于 2024-04-20 06:06:10

您必须使用interactive onplt.draw
这里有一个有效的例子。
由于我没有你的算法来生成你的G图,我将粗略地画出相同的网络。不管怎样,每次打给nx.绘制(G) 创建一个不同的图形,您可以看到它在每次调用时更新绘图。在

import matplotlib.pyplot as plt
import time
import networkx as nx

plt.ion()   # call interactive on

data = [(0, 1), (1, 2), (1, 4), (1, 9), (2, 6), (3, 5), (5, 7), (5, 8), (5, 10)]

# I create a networkX graph G
G = nx.Graph()
for item, (a, b) in enumerate(data):
    G.add_node(item)
    G.add_edge(a,b)

# make initial plot and set axes limits.
# (alternatively you may want to set this dynamically)
plot, = plt.plot([], [])
plt.xlim(-1, 3)
plt.ylim(-1, 3)

# here is the plotting stage.
for _ in range(10):           # plot 10 times
    plt.cla()                 # clear the previous plot
    nx.draw(G)
    plt.draw()
    time.sleep(2)             # otherwise it runs to fast to see

相关问题 更多 >