我得到了散点图。现在我想尝试动画。我查看了多个文档,了解如何执行此操作。我得到了散点图的动画,但没有一个点位于正确的位置。我相信我误解了如何使用set_offsets,但我不知道是什么。
以下是调用matplotlib的类中的代码。它将代理设置在初始图中的正确位置:
def plot(self):
Show where agents are in graphical form. -------------------------- 2---
data = self.plot_data()
disp.display_scatter_plot("Agent Positions", data, anim=True,
data_func=self.plot_data)
def plot_data(self):
data = {}
for v in self.agents.varieties_iter():
data[v] = {"x": [], "y": []}
for agent in self.agents.variety_iter(v):
x_y = self.get_pos_components(agent)
data[v]["x"].append(x_y[0])
data[v]["y"].append(x_y[1])
return data
这是我尝试动画这个情节:
def display_scatter_plot(title, varieties, anim=False,
data_func=None):
"""
Display a scatter plot.l
varieties is the different types of
entities to show in the plot, which
will get assigned different colors
"""
def update_plot(i):
varieties = data_func()
for var, scat in zip(varieties, scats):
x = np.array(varieties[var]["x"])
y = np.array(varieties[var]["y"])
scat.set_offsets((x, y))
return scats
fig, ax = plt.subplots()
scats = []
i = 0
for var in varieties:
color = colors[i % NUM_COLORS]
x = np.array(varieties[var]["x"])
y = np.array(varieties[var]["y"])
scat = plt.scatter(x, y, c=color, label=var,
alpha=0.9, edgecolors='none')
scats.append(scat)
i += 1
ax.legend()
ax.set_title(title)
plt.grid(True)
if anim:
animation.FuncAnimation(fig,
update_plot,
frames=1000,
interval=1000,
blit=False)
plt.show(block=False)
一旦动画开始,点就会移动,但正如我所提到的,它们都没有到正确的位置!正如我所说,我认为我的set_offsets错误,但我不知道我是怎么做的。