Matplotlib: 使用canvas.draw()重新绘制3D图形时添加额外的坐标轴

4

我有一个可能非常简单的问题,需要使用Matplotlib重新绘制一些3D数据。最初,我在画布上有一个带有3D投影的图形:

self.fig = plt.figure()
self.canvas = FigCanvas(self.mainPanel, -1, self.fig)
self.axes = self.fig.add_subplot(111, projection='3d')

enter image description here

我添加了一些数据并使用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')

嗨Joaquin, 感谢你抽出时间回复。我尝试了这个方法,但似乎不起作用。remove()函数似乎可以清除3D散点图数据,但对坐标轴没有任何影响。此外,2D坐标轴(在图形外部的-0.05到0.05)仍然存在。还有其他想法吗? - Dan
2D轴的标签本来就不应该存在。你从代码中删除了axes.clear()这行吗? - joaquin
嗨, 是的,我做到了。第一次绘制时,2D轴不存在。但第二次,它们再次出现。代码如下: xs = np.random.random_sample(100)*40 - 20 ys = np.random.random_sample(100)*40 - 20 zs = np.random.random_sample(100)*40 - 20 a = self.axes.scatter(xs, ys, zs, c='r', marker='o') a.remove() a = self.axes.scatter(xs, ys, zs, c='r', marker='o') self.canvas.draw() - Dan
@Dan Pearce 我进行了编辑并添加了一些行,以防止误解。也许现在的问题在于你的canvas.draw()。我不使用任何画布来绘制。 - joaquin
如果我只使用remove()函数,2D轴不会出现,但是之前绘制的数据并没有被清除。如果我在其中任何地方使用ax.cla()、ax.clf()、ax.hold(True)、ax.hold(False)或ax.clear(),2D轴就会出现。显然我在这里漏掉了什么... - Dan
让我们在聊天室中继续这个讨论 - Dan

2

Joquin的建议很有效,突显了我可能一开始就错误地绘制图表。但为了完整起见,我最终发现你可以通过以下方式简单地去除2D轴:

self.axes.get_xaxis().set_visible(False)
self.axes.get_yaxis().set_visible(False)

这至少是一种从3D图中移除2D标签的方法,如果它们出现了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接