我有两个数据集,我想用不同的颜色生成散点图。
遵循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)坐标,并将它们分配给正确的数据集,以便对它们进行不同的着色。
我已经尝试过清理和重绘,但我似乎无法让它工作。
编辑:稍作澄清。我想要做的基本上是在同一个地块上制作两个散点图。
答案 0 :(得分: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。您可以在那里动画散点图中学习更多调整。