matplotlib 数据点随时间的交互式绘图更新

thtygnil  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(132)

我有一个3D坐标的数据集在时间上移动。所以我的ndarray数据看起来像这样:

  1. points = [ # 1st dim: Time-step (/timeframe)
  2. [ # 2nd dim: Different Objects
  3. [ # 3rd dim: The coordinates of the Objects
  4. 2.115, 2.387, 3.3680003],
  5. [2.059, 2.302, 3.2610002],
  6. [2.1720002 2.2280002 3.1880002]],
  7. [[1.9530001, 2.306, 3.5760002],
  8. [1.9510001, 2.265, 3.433 ],
  9. [2.1000001, 2.2440002, 3.381]],
  10. [[1.6760001, 2.459, 3.4650002],
  11. [1.5710001, 2.434, 3.367 ],
  12. [1.6320001 2.4320002 3.2250001]]]

我正在绘制一个接一个的对象:

  1. import matplotlib.pyplot as plt
  2. for timeframe in range(points.shape[0]):
  3. fig = plt.figure()
  4. ax = fig.add_subplot(111, projection='3d')
  5. x_coordinates = points[timeframe][:, 0]
  6. y_coordinates = points[timeframe][:, 1]
  7. z_coordinates = points[timeframe][:, 2]
  8. ax.scatter(x_coordinates, y_coordinates, z_coordinates, c='r', marker='o')
  9. plt.show()

现在我想制作一个图或窗口,在这里我可以使用滑块根据时间步长在绘制的图形之间进行选择。

是否有任何代码或python模块,用于在for循环中选择图,例如通过滑块?

v440hwme

v440hwme1#

是的,你可以使用matplotlib widgets库,但是你需要让你的matplotlib具有交互性。
您可以添加一个水平滑块(参见示例:https://matplotlib.org/stable/gallery/widgets/slider_demo.html),当您选择并移动滑块时,您将调用一个函数。在我提供的示例中,该函数称为update。当您通过移动滑块来更新滑块值时,它将调用此函数并将实际滑块值提供给它。
所以你可以用你的for loop的整数值创建一个滑块,当你更新滑块时,你调用update函数,在里面你有代码来使用来自滑块的整数值绘制数据。

滑块

  1. axfreq = plt.axes([0.25, 0.1, 0.65, 0.03])
  2. freq_slider = Slider(
  3. ax=axfreq,
  4. label='Time Steps',
  5. valmin=0, # minimun value of range
  6. valmax=points.shape[0] - 1, # maximum value of range
  7. valinit=0,
  8. valstep=1.0 # step between values
  9. )

当你看到我分享的例子时,我保留了几乎所有的名字来帮助你。请注意,当你滑动滑块时,我添加了valstep=1.0以增加1。

更新功能

  1. def update(val)
  2. val = int(val) # it must be an integer
  3. fig = plt.figure()
  4. ax = fig.add_subplot(111, projection='3d')
  5. x_coordinates = points[val][:, 0]
  6. y_coordinates = points[val][:, 1]
  7. z_coordinates = points[val][:, 2]
  8. ax.scatter(x_coordinates, y_coordinates, z_coordinates, c='r', marker='o')
  9. plt.show()

它可能会出现一些问题,因为你可能没有你的matplotlib交互。如果你使用jupyter-notebook很容易把它交互,你只需要添加这行在顶部:

  1. %matplotlib widget

如果不起作用,您可以尝试:

  1. %matplotlib notebook

您可能还需要安装一些apache模块。
如果你想让它恢复正常,你只需要在顶部再次添加:

  1. %matplotlib inline

关于matplotlib中交互式绘图的更多信息:https://matplotlib.org/stable/users/explain/interactive.html

展开查看全部

相关问题