2016-03-05 137 views
0

我有两个数据集,我想用不同的颜色为散点图生成散点图。Matplotlib:更新循环中的多个散点图

MatPlotLib: Multiple datasets on the same scatter plot

我设法绘制他们的意见。但是,我希望能够更新会影响两组数据的循环内的散点图。我查看了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)COORDS,并将它们分配到正确的数据集所以他们可以有不同的颜色。

我试过清理和重绘,但我似乎无法得到它的工作。

编辑:稍微澄清。我想要做的基本上是在同一个图上动画两个散点图。

+0

'scatter命令之后可能需要'plt.show()',通常在循环之外。 – roadrunner66

+0

如果它在循环之外,是不是只会更新一次数字,或者更糟糕的是,在最终的数字上添加每个散点图(在这种情况下是2 * gen)? – Gsp

回答

1

下面是可能适合你的描述代码:

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。您可以通过动画设计散点图来了解更多细节。

+0

感谢您的帮助,但它不是很有效。我应该提到这一点,但我有一个主要方法,所以我得到了一些范围问题(如定义之前调用更新)。我试着玩弄它,但似乎无法弄清楚。 – Gsp