根据实时用户输入更新Matplotlib

根据实时用户输入更新Matplotlib

本文介绍了根据实时用户输入更新Matplotlib 3D图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让matplotlib根据用户输入创建动态3d图形-但是我无法更新图形。如果我使用完全相同的代码,但没有设置 projection ='3d',则该程序可以正常运行-但只要将图形更改为以3d形式显示,它就无法正常工作。

I am trying to get matplotlib to create a dynamic 3d graph based on user input - but I can't get the graph to update. If I use the exact same code but without the "projection='3d'" setting, the program works correctly - but as soon as the graph is changed to display in 3d - it doesn't work.

任何帮助将不胜感激。

3D图形代码(图形未更新)

3D Graph Code (graph doesn't update)

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

plt.subplots_adjust(left=0.25, bottom=0.25)

x = np.arange(0.0, 1.0, 0.1)
a0 = 5
b0 = 1
y = a0 * x + b0
z = np.zeros(10)

l, = plt.plot(x, y, z)

# Set size of Axes
plt.axis([0, 1, -10, 10])

# Place Sliders on Graph
ax_a = plt.axes([0.25, 0.1, 0.65, 0.03])
ax_b = plt.axes([0.25, 0.15, 0.65, 0.03])

# Create Sliders & Determine Range
sa = Slider(ax_a, 'a', 0, 10.0, valinit=a0)
sb = Slider(ax_b, 'b', 0, 10.0, valinit=b0)


def update(val):
    a = sa.val
    b = sb.val
    l.set_ydata(a*x+b)
    fig.canvas.draw_idle()

sa.on_changed(update)
sb.on_changed(update)

plt.show()

2D图形代码(正确更新图形)

2D Graph Code (graph updates properly)

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = fig.add_subplot(111)

plt.subplots_adjust(left=0.25, bottom=0.25)

x = np.arange(0.0, 1.0, 0.1)
a0 = 5
b0 = 1
y = a0 * x + b0

l, = plt.plot(x, y)

# Set size of Axes
plt.axis([0, 1, -10, 10])

# Place Sliders on Graph
ax_a = plt.axes([0.25, 0.1, 0.65, 0.03])
ax_b = plt.axes([0.25, 0.15, 0.65, 0.03])

# Create Sliders & Determine Range
sa = Slider(ax_a, 'a', 0, 10.0, valinit=a0)
sb = Slider(ax_b, 'b', 0, 10.0, valinit=b0)


def update(val):
    a = sa.val
    b = sb.val
    l.set_ydata(a*x+b)
    fig.canvas.draw_idle()

sa.on_changed(update)
sb.on_changed(update)

plt.show()


推荐答案

3D案例中的行需要在所有3个维度上进行更新(即使其中的数据一些尺寸保持不变)。为此,必须使用 set_data 设置2D数据,并使用 set_3d_properties 设置第三维。所以更新 y 看起来像这样:

The line in the 3D case needs to be updated in all 3 dimensions (even the data in some dimension stays the same). In order to do so, you have to set the 2D data using set_data and the third dimension using set_3d_properties. So updating y would look like this:

l.set_data(x, a*x+b)
l.set_3d_properties(z)

这篇关于根据实时用户输入更新Matplotlib 3D图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 00:29