【问题标题】:Dynamic edge addition in network using matplotlib [duplicate]使用matplotlib在网络中添加动态边缘[重复]
【发布时间】:2018-06-12 21:26:03
【问题描述】:

我试图通过将边缘连接到不同节点来模拟网络增长。以下代码在运行时会同时显示整个边和节点序列。 但是我如何在延迟 n 个单位时间后显示一条边被添加到另一条边(在同一张图中)。我知道我必须使用“动画”包,但不确定如何 p>

import networkx as nx
import matplotlib.pyplot as plt

def f1(g):

    nodes = set([a for a, b in g] + [b for a, b in g])

    G=nx.Graph()

    for node in nodes:
       G.add_node(node)

    for edge in g:
       G.add_edge(edge[0], edge[1])

    pos = nx.shell_layout(G)

    nx.draw(G, pos)

    plt.show()

g = [(10, 11),(11, 12),(12, 13), (13, 15),(15,10)]
f1(g)

我希望意图是正确的。运行代码时,确实会显示一个图形,但是如何让每条边一个接一个地出现,而不是同时出现。

【问题讨论】:

  • 您发布的代码无法运行——能否将您的问题表述为Minimal, Complete, and Verifiable example
  • 我差点错过你的编辑——下次最好回复评论。如果您以@开始您的评论,后跟用户名,该用户将在其邮箱中收到一条注释。

标签: python matplotlib animation networkx


【解决方案1】:

这个问题here 基本上已经有了答案,但我决定再写一个针对您的具体问题量身定制的答案。我没有使用nx.draw(),而是使用nx.draw_networkx_edgesdraw_networkx_nodes,它们分别返回LineCollectionsPathCollection。然后可以通过多种方式更改它们,例如您可以更改LineCollection 中每个线段的颜色。一开始我将所有边的颜色设置为white,然后我使用matplotlib.animation.FuncAnimation在给定的时间间隔将这些段颜色一一更改为black。一旦所有边缘都变黑,动画就会重新开始。希望这会有所帮助。

import networkx as nx
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

g = [(10, 11),(11, 12),(12, 13), (13, 15),(15,10)]

fig = plt.figure()

G = nx.Graph()
G.add_edges_from(g)
G.add_nodes_from(G)

pos = nx.shell_layout(G)
edges = nx.draw_networkx_edges(G, pos, edge_color = 'w')
nodes = nx.draw_networkx_nodes(G, pos, node_color = 'g')

white = (1,1,1,1)
black = (0,0,0,1)

colors = [white for edge in edges.get_segments()]

def update(n):
    global colors

    try:
        idx = colors.index(white)
        colors[idx] = black
    except ValueError:
        colors = [white for edge in edges.get_segments()]

    edges.set_color(colors)
    return edges, nodes

anim = FuncAnimation(fig, update, interval=150, blit = True) 

plt.show()

结果如下:

【讨论】:

  • 所以白色和黑色的颜色边缘相互重叠!!非常感谢!!!
猜你喜欢
  • 1970-01-01
  • 2020-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-26
  • 1970-01-01
  • 2015-09-14
相关资源
最近更新 更多