【问题标题】:How to plot graphs iteratively on Jupyter Notebook如何在 Jupyter Notebook 上迭代地绘制图形
【发布时间】:2019-10-14 08:12:28
【问题描述】:

我正在使用增量图,所以我想在每次在上一张图的顶部插入新边时绘制当前图。

使用此代码,我可以一次生成一个图形,但它们仅在迭代结束后才会显示。

import random
import time
import networkx as nx
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook

#Generating some random edges
M = 10
N = 4
edges = []
for i in range(M):
    s = random.randrange(N) + 1
    t = random.randrange(N) + 1
    edges.append((s,t))

G = nx.DiGraph()
G.add_nodes_from(range(1, 5))

plt.subplot(121)
plt.ion()

nx.draw(G, with_labels=True, font_weight='bold')

for edge in edges:
    plt.figure()
    G.add_edge(*edge)
    nx.draw(G, with_labels=True, font_weight='bold')
    time.sleep(1)

但我真正想要的是看到在每次迭代时重新绘制图形,或者至少能够使用 Matplotlib 的交互模式将它们堆叠起来,这样我就可以前进和后退。

我已经搜索了好几天,发现了一些使用条形图、饼图等图表的示例,但我的意思是图表是数据结构,而不是图表。

【问题讨论】:

  • plt.draw() 将更新交互式绘图。 plt.pause(...) 会添加一个暂停。 time.sleep(1) 只会阻止 python 一秒钟,这在这里没有多大意义。
  • 嗯,这很有趣,但即使使用“plt.pause”,图表也不会在暂停时间内显示。
  • 哦,我刚刚看到你每秒钟都会创建一个新人物。这肯定没有帮助。
  • 好吧,我可以使用IPython.display.clear_output() 清除屏幕,但在暂停时间间隔内没有绘制任何内容。 Matplotlib 的交互模式显然可以选择在单帧中堆叠视图,但我不知道该怎么做。

标签: python matplotlib graph jupyter-notebook networkx


【解决方案1】:

这里有一个使用FuncAnimation的建议,大大简化了matplotlib中创建动画/实时图的整个过程

import random
import time
import networkx as nx
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook

#Generating some random edges
M = 10
N = 4
edges = []
for i in range(M):
    s = random.randrange(N) + 1
    t = random.randrange(N) + 1
    edges.append((s,t))

G = nx.DiGraph()
G.add_nodes_from(range(1, 5))

fig = plt.figure()
ax = plt.subplot(121)

def init():
    nx.draw(G, with_labels=True, font_weight='bold')

def update(edge):
    G.add_edge(*edge)
    nx.draw(G, with_labels=True, font_weight='bold')

ani = animation.FuncAnimation(fig, update, frames=edges, interval=1000., init_func=init, repeat=False)

【讨论】:

  • 非常感谢,这正是我想要的。我只是在更新方法上添加了plt.cla(),以便在绘制下一个之前清除上一个图形。
  • 不客气。如果您认为您的问题已解决,请考虑使用左侧的复选标记接受答案以关闭此主题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-10
  • 2018-01-28
  • 2018-11-15
  • 1970-01-01
  • 2023-03-26
相关资源
最近更新 更多