LineCollection为此最容易使用。这样,您可以将所有颜色设置为单个阵列,并且通常可以获得更好的绘图性能。
更好的性能主要是因为集合是在matplotlib中绘制许多相似对象的优化方法。在这种情况下,避免嵌套循环来设置颜色实际上是次要的。
考虑到这一点,请尝试以下方法:
import numpy as npfrom matplotlib import pyplot as pltfrom matplotlib.collections import LineCollectionimport matplotlib.animation as animationlines=[]for i in range(10): for j in range(10): lines.append([(0, i), (1, j)])fig, ax = plt.subplots()colors = np.random.random(len(lines))col = LineCollection(lines, array=colors, cmap=plt.cm.gray, norm=plt.Normalize(0,1))ax.add_collection(col)ax.autoscale()def update(i): colors = np.random.random(len(lines)) col.set_array(colors) return col,# Setting this to a very short update interval to show rapid drawing.# 25ms would be more reasonable than 1ms.ani = animation.FuncAnimation(fig, update, interval=1, blit=True, init_func=lambda: [col])# Some matplotlib versions explictly need an `init_func` to display properly...# Ideally we'd fully initialize the plot inside it. For simplicitly, we'll just# return the artist so that `FuncAnimation` knows what to draw.plt.show()



