Update Matplotlib 3D Graph Based on Real Time User

2019-08-02 16:49发布

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.

Any help would be greatly appreciated.

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

1条回答
Anthone
2楼-- · 2019-08-02 17:39

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)
查看更多
登录 后发表回答