我有一个问题,类似于这个问题,但是我要绘制少量的点和边(至少是10倍),并希望对它们进行动画处理。更具体地说,这是一个Kohonen网络在2D地图上的可视化,它会演变成一个变形的正方形晶格,参见维基百科中的这张图片:
接着,发生了一次更新,改变了这些点的坐标:
我希望避免“愚蠢”的重新绘制所有内容的方法,因为图形窗口中还有其他数据没有变化,而且这样做会非常慢:
作为第一步,我将初始图中创建的Line2D数据保存在变量
import numpy as np
import matplotlib.pyplot as plt
def getXY(points, edges):
"""Return x and y arrays to pass to the plot function"""
return [points.T[i][edges.T] for i in np.arange(points.shape[1])]
points = numpy.array([[1,2],[4,5],[2,7],[3,9],[9,2]])
edges = numpy.array([[0,1],[3,4],[3,2],[2,4]])
lines = plt.plot(*getXY(points, edges), linestyle='-', color='y',
markerfacecolor='red', marker='o')
plt.show()
接着,发生了一次更新,改变了这些点的坐标:
points += 1 # simplified version of a real update
我希望避免“愚蠢”的重新绘制所有内容的方法,因为图形窗口中还有其他数据没有变化,而且这样做会非常慢:
# repeat after each update all the calculation
plt.cla()
x, y = [points.T[i][edges.T] for i in np.arange(points.shape[1])]
lines = plt.plot(x, y, linestyle='-', color='y',
markerfacecolor='red', marker='o')
plt.show()
作为第一步,我将初始图中创建的Line2D数据保存在变量
lines
中。
我现在面临的问题是,如果我只想更新线条数据,我能想到的唯一解决方案就是需要迭代所有线条,这看起来不太优雅。x, y = getXY(points, edges)
if len(lines) > 1:
for i, d in enumerate(zip(x.T, y.T)):
lines[i].set_data(d)
else: # has to be treated seperately, since the format of x and y is different
lines[0].set_data(x, y)
plt.show()
我正在寻找如何改进以下方面的建议:
- 提出比我的for循环更好的解决方案
- 提供在更加优雅的方式下解决初始问题的想法(即以指定连接绘制点)