使用canvas.draw()重新绘制3D图时如何添加额外坐标轴
我遇到了一个可能很简单的问题,想用Matplotlib重新绘制一些3D数据。最开始,我在画布上有一个3D的图像:
self.fig = plt.figure()
self.canvas = FigCanvas(self.mainPanel, -1, self.fig)
self.axes = self.fig.add_subplot(111, projection='3d')
然后我添加了一些数据,并使用canvas.draw()来更新图像。图表本身按预期更新了,但我发现图的外面多出了额外的2D坐标轴(范围是-0.05到0.05),我不知道怎么去掉它:
self.axes.clear()
self.axes = self.fig.add_subplot(111, projection='3d')
xs = np.random.random_sample(100)
ys = np.random.random_sample(100)
zs = np.random.random_sample(100)
self.axes.scatter(xs, ys, zs, c='r', marker='o')
self.canvas.draw()
有没有什么想法?我现在有点迷茫!
2 个回答
3
与其使用 axes.clear()
和 fig.add_subplot
,不如直接使用 mpl_toolkits.mplot3d.art3d.Patch3DCollection
对象的 remove
方法:
In [31]: fig = plt.figure()
In [32]: ax = fig.add_subplot(111, projection='3d')
In [33]: xs = np.random.random_sample(100)
In [34]: ys = np.random.random_sample(100)
In [35]: zs = np.random.random_sample(100)
In [36]: a = ax.scatter(xs, ys, zs, c='r', marker='o') #draws
In [37]: a.remove() #clean
In [38]: a = ax.scatter(xs, ys, zs, c='r', marker='o') #draws again
如果你还有问题,可以试试这个:
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import interactive
interactive(True)
xs = np.random.random_sample(100)
ys = np.random.random_sample(100)
zs = np.random.random_sample(100)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
a = ax.scatter(xs, ys, zs, c='r', marker='o')
plt.draw()
raw_input('press for new image')
a.remove()
xs = np.random.random_sample(1000)
ys = np.random.random_sample(1000)
zs = np.random.random_sample(1000)
a = ax.scatter(xs, ys, zs, c='r', marker='o')
plt.draw()
raw_input('press to end')
2
Joquin的建议很有效,让我意识到我一开始可能在绘图的方法上走错了方向。不过,为了完整起见,我最终发现可以通过以下方式去掉2D坐标轴:
self.axes.get_xaxis().set_visible(False)
self.axes.get_yaxis().set_visible(False)
这似乎是去掉3D图中出现的2D标签的一种方法。