基于实时用户输入更新Matplotlib 3D图形

时间:2017-03-27 06:03:15

标签: matplotlib 3d widget slider python-3.4

我正在尝试让matplotlib根据用户输入创建一个动态的3d图形 - 但是我无法让图形更新。如果我使用完全相同的代码,但没有"投影=' 3d'"设置,程序正常工作 - 但一旦图形更改为在3d中显示 - 它不起作用。

非常感谢任何帮助。

3D图形代码(图形不会更新)

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图形代码(图形正确更新)

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()

1 个答案:

答案 0 :(得分:1)

3D情况下的线需要在所有3个维度中更新(即使某些维度中的数据保持不变)。为此,您必须使用set_data设置2D数据,使用set_3d_properties设置第三维。因此,更新y将如下所示:

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