我在散点图中有一堆重叠的点。我正在使用 FuncAnimation 来创建动画。在连续的帧中,我想更改出现在其他帧前面的帧。
作为一个简单的 MCVE,请考虑下面的代码,其中每个帧使一组不同的点变为红色。然而,这些红点通常很大程度上被其他点遮挡。我想让这些红点出现在前面。
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import random
def update(time, plotted_points, N):
#in here I would like to update the order that the points are plotted in. I would like the red points to come to the front.
color_change_indices = set(random.choices(range(N), k=1000))
colors = ['red' if n in color_change_indices else 'gray' for n in range(N)]
plotted_points.set_color(colors)
return plotted_points
def animate(N):
x = [random.random() for val in range(N)]
y = [random.random() for val in range(N)]
fig = plt.figure()
ax = fig.add_subplot(111)
plotted_points = ax.scatter(x, y, color='gray')
fargs = (plotted_points, N)
ani = FuncAnimation(fig, update, frames = range(100), fargs = fargs)
plt.show()
animate(10000)
我可以改变它们的颜色。我可以移动他们的坐标。但是,到目前为止我无法修改它们的相对深度。
到目前为止,我最好的想法是,也许我应该删除绘制的点,然后重新绘制它们。但我对 matplotlib 没有深入的了解,到目前为止我尝试删除它们都失败了。
最佳答案
您可以有第二个散点
图,红色且具有更高的zorder
,并更新其点:
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import random
plt.ion()
def update(time, red_plotted_points, points, N):
indexes = set([random.choice(range(N)) for i in range(int(N/2))]) # for instance!
new_points = [points[i] for i in indexes]
red_plotted_points.set_offsets(new_points)
def animate(N):
x = [random.random() for val in range(N)]
y = [random.random() for val in range(N)]
points = [[x[i], y[i]]for i in range(N)]
fig = plt.figure()
ax = fig.add_subplot(111)
plotted_points = ax.scatter(x, y, color='gray', zorder=1)
red_plotted_points = ax.scatter([], [], color='red', zorder=2) # starts empty
fargs = (red_plotted_points, points, N)
ani = FuncAnimation(fig, update, frames=range(100), fargs=fargs,
interval=200, repeat=True)
ani._start()
fig.show()
return fig, ani
if __name__ == '__main__':
fig, ani = animate(100)
(python 2.7.14,matplotlib 2.1.1)
Edit: Updated to also run on Python 3.6.3, matpotlib 2.1.0
我不知道为什么,但似乎如果没有保留对 FuncAnimation
的引用,它在 Python 3.6 上不起作用。感谢 Joel(评论)的关注。
关于python - 如何在动画的散点图中重新排序节点(更改深度),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48055581/