我有两个数据集,我想为其生成不同颜色的散点图。
我成功地绘制了它们。但是,我希望能够更新循环内的散点图,这将影响两组数据。我查看了 matplotlib 动画包,但它似乎不符合要求。
我无法让绘图在循环内更新。
代码结构如下:
fig = plt.figure()
ax1 = fig.add_subplot(111)
for g in range(gen):
# some simulation work that affects the data sets
peng_x, peng_y, bear_x, bear_y = generate_plot(population)
ax1.scatter(peng_x, peng_y, color = 'green')
ax1.scatter(bear_x, bear_y, color = 'red')
# this doesn't refresh the plots
generate_plot() 从带有附加信息的 numpy 数组中提取相关绘图信息 (x,y) 坐标,并将它们分配给正确的数据集,以便它们可以具有不同的颜色。
我尝试过清除和重绘,但似乎无法使其工作。
编辑:稍微澄清一下。我想做的基本上是在同一个图上制作两个散点图的动画。
这是可能符合您的描述的代码:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# Create new Figure and an Axes which fills it.
fig = plt.figure(figsize=(7, 7))
ax = fig.add_axes([0, 0, 1, 1], frameon=False)
ax.set_xlim(-1, 1), ax.set_xticks([])
ax.set_ylim(-1, 1), ax.set_yticks([])
# Create data
ndata = 50
data = np.zeros(ndata, dtype=[('peng', float, 2), ('bear', float, 2)])
# Initialize the position of data
data['peng'] = np.random.randn(ndata, 2)
data['bear'] = np.random.randn(ndata, 2)
# Construct the scatter which we will update during animation
scat1 = ax.scatter(data['peng'][:, 0], data['peng'][:, 1], color='green')
scat2 = ax.scatter(data['bear'][:, 0], data['bear'][:, 1], color='red')
def update(frame_number):
# insert results from generate_plot(population) here
data['peng'] = np.random.randn(ndata, 2)
data['bear'] = np.random.randn(ndata, 2)
# Update the scatter collection with the new positions.
scat1.set_offsets(data['peng'])
scat2.set_offsets(data['bear'])
# Construct the animation, using the update function as the animation
# director.
animation = FuncAnimation(fig, update, interval=10)
plt.show()
您可能还想看看 http://matplotlib.org/examples/animation/rain.html。您可以在那里了解有关散点图动画的更多调整。