我想动画一个随时间增长的图形。
这是我到目前为止所拥有的:
fig = plt.figure() ims = [] graph = nx.Graph() for i in range(50): // Code to modify Graph nx.draw(graph, pos=nx.get_node_attributes(graph,'Position')) im = plt.draw() self.ims.append([im]) ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True,repeat_delay=1000) ani.save('dynamic_images.mp4') plt.show()
但是,我收到以下错误消息:
File "main.py", line 204, in <module> repeat_delay=1000) File "/usr/lib/pymodules/python2.7/matplotlib/animation.py", line 356, in __init__ TimedAnimation.__init__(self, fig, *args, **kwargs) File "/usr/lib/pymodules/python2.7/matplotlib/animation.py", line 304, in __init__ Animation.__init__(self, fig, event_source=event_source, *args, **kwargs) File "/usr/lib/pymodules/python2.7/matplotlib/animation.py", line 53, in __init__ self._init_draw() File "/usr/lib/pymodules/python2.7/matplotlib/animation.py", line 363, in _init_draw artist.set_visible(False) AttributeError: 'NoneType' object has no attribute 'set_visible' nicomoto@nicomoto-VirtualBox:~/Desktop/CS8903-SpecialProblem/Code/
我想要的是一个动画,您可以在其中看到图形的增长。我可以在每个阶段保存图形,也许可以在matplotlib之外创建动画,但是有什么办法可以使它像这样工作吗?
经过审查,该代码与该问题的相关性不如我想象的那样。但是,我能够使用该SO答案和该SO答案为您拼凑出一个答案。以下代码将创建一个图,向其中添加50个随机节点和50个随机边,并在添加每个节点和边后显示图的图像。代码中的一些关键更改:
pylab.ion()
matplotlib.pyplot.pause()
time.sleep()
祝好运!
import random import pylab from matplotlib.pyplot import pause import networkx as nx pylab.ion() graph = nx.Graph() node_number = 0 graph.add_node(node_number, Position=(random.randrange(0, 100), random.randrange(0, 100))) def get_fig(): global node_number node_number += 1 graph.add_node(node_number, Position=(random.randrange(0, 100), random.randrange(0, 100))) graph.add_edge(node_number, random.choice(graph.nodes())) fig = pylab.figure() nx.draw(graph, pos=nx.get_node_attributes(graph,'Position')) return fig num_plots = 50; pylab.show() for i in range(num_plots): fig = get_fig() fig.canvas.draw() pylab.draw() pause(2) pylab.close(fig)