matplotlib scatter colorbar 产生奇怪的视觉伪像

matplotlib scatter colorbar produces strange visual artifacts

我正在尝试将颜色条添加到 3-D 散点图。它实际上是有效的,只是在随后调用该函数时,颜色条将旧的刻度标签留在屏幕上并在它们上面写上新标签,将标签变成视觉意大利面条。调用 cbar.ax.clear() 没有帮助。此外,图表未显示 X、Y 和 Z 标签,并且从 canvas 的边缘下方几乎看不到一点文本。我确定我做错了顺序,但我不知道是什么。

def mplPlotColorCloud(figure, canvas, vals, xlabel, ylabel, zlabel):
xvect = [val[0] for val in vals]
yvect = [val[1] for val in vals]
zvect = [val[2] for val in vals]
valvect = [val[3] for val in vals]
ax = figure.add_subplot(111, projection='3d')
# discards the old graph
ax.hold(False)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
ax.set_zlabel(zlabel)
cax = ax.scatter(xvect, yvect, zvect, c=valvect, cmap=None)
# Make a colorbar
minval = np.min(valvect)
maxval = np.max(valvect)
if minval != maxval:
    ticks = list(np.linspace(minval, maxval, num=3))
    tickLabels = [str(np.round(x,2)) for x in ticks]    
    cbar = figure.colorbar(cax, ticks=ticks, orientation='vertical')
    cbar.ax.set_xticklabels(tickLabels)
else:
    figure.colorbar(cax, orientation='vertical')        
canvas.draw()

我想通了。在 figure.add_subplot() 之前调用 figure.clear() 是确保删除所有视觉伪像所必需的。