【问题标题】:Matplotlib: updating multiple scatter plots in a loopMatplotlib:循环更新多个散点图
【发布时间】:2016-06-19 00:00:44
【问题描述】:

我想为两个数据集生成不同颜色的散点图。

遵循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) 坐标,并将它们分配给正确的数据集,以便它们可以被不同地着色。

我已尝试清除和重绘,但似乎无法正常工作。

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

【问题讨论】:

  • plt.show() 可能需要在分散命令之后,通常在循环之外。
  • 如果它在循环之外,它会不会只更新一次图形,或者更糟糕的是,将每个散点图(在这种情况下为 2 * gen of them)叠加在最终图形上?跨度>

标签: python animation matplotlib


【解决方案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。您可以在此处了解更多动画散点图的调整。

【讨论】:

  • 感谢您的帮助,但它不太有效。我应该提到这一点,但我有一个主要方法,所以我遇到了一些范围问题(比如在定义之前调用了更新)。我试过玩弄它,但似乎无法弄清楚。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-20
  • 2017-08-01
  • 1970-01-01
  • 2019-11-23
相关资源
最近更新 更多