我希望 MatPlotLib 中的 3D 散点图在 Jupyter Python 笔记本中以交互方式旋转。出于这个原因,我集成了一个滑块ipywidgets
来更新视角。下面的测试代码显示了我想要实现的目标。问题是在前一个数字下方添加了一个新数字,而不是清除当前数字。我试过了plt.close(fig)
,plt.cla()
但plt.clf()
没有成功。(进一步我意识到重新创建图形和轴有开销,但这是我目前关注的较小部分......)
这是(测试)代码:
# init
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import ipywidgets as widgets
from IPython.display import display
# generate test data
x = np.random.rand(100)
y = np.random.rand(100)
z = np.random.rand(100)
# prepare plot
def draw_plot(angle1 = 20, angle2 = 40):
# create figure
fig = plt.figure(figsize=(15,10))
ax = fig.add_subplot(111, projection='3d')
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
ax.scatter(x, y, z)
# set view angle
ax.view_init(angle1, angle2)
# show plot
plt.show()
# prepare widgets
angle1_slider = widgets.IntSlider(20, min = 0, max = 60)
angle1_label = widgets.Label(value = 'Angle 1 value is: ' + str(angle1_slider.value))
display(angle1_slider, angle1_label)
# handle angle 1 update
def update_angle1(value):
draw_plot(angle1 = value['new'])
angle1_label.value = 'Angle 1 value is: ' + str(value.new)
angle1_slider.observe(update_angle1, names = 'value')
# draw initial plot
draw_plot()
任何建议,将不胜感激!