我已经构建了一个程序,可以在直接输出到 Matplotlib 时根据输入数据成功创建格式正确的 3D 直方图。然而,当我最近尝试将相同的代码输出到 Qt Designer 内的 MatplotlibWidget 时,网格线总是显示在 3D 图的前面,除非我将它们从图中完全删除。
好直方图:
坏直方图:
两者都使用基本相同的代码。我尝试更改绘制不同元素的顺序,尝试 set_axisbelow(),但没有任何帮助,并尝试更改 zorder,但没有任何明显影响。唯一有效的是 grid(b=False),它会完全关闭线条,但我更愿意将它们留在里面,因为没有它们很难从 3D 图形中获得准确的值。
这是有问题的代码:
def plotHist(self, xVals, yVals, zVals, cVals, targetWidget):
targetWidget.canvas.ax.clear()
targetWidget.canvas.ax.grid(b=True, zorder=2)
x = np.array(xVals[1:], dtype=np.float)
y = np.array(yVals[1:], dtype=np.float)
if np.max(x) !=0.0:
x = x[np.nonzero(x)]
y = y[np.nonzero(y)]
histPlot = targetWidget.canvas.ax
hist, xedges, yedges = np.histogram2d(x, y, bins=self.binNum)
hist = np.rot90(hist, k=3)
hist = np.fliplr(hist)
elements = (len(xedges) - 1) * (len(yedges) - 1)
xpos, ypos = np.meshgrid(xedges[:-1], yedges[:-1])
xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(elements)
xwidth = abs(xedges[0]-xedges[1])
ywidth = abs(yedges[0]-yedges[1])
dx = xwidth * np.ones_like(zpos)
dy = ywidth * np.ones_like(zpos)
dz = hist.flatten()
xbottom = xedges[0] - xwidth*self.histPad
xtop = xedges[-1] + xwidth*self.histPad
ybottom = yedges[0] - ywidth*self.histPad
ytop = yedges[-1] + ywidth*self.histPad
histPlot.bar3d(xpos, ypos, zpos, dx, dy, dz, color='Tomato', alpha=0.8, zsort='max',zorder=1)
histPlot.set_xlim(xbottom, xtop)
histPlot.set_ylim(ybottom, ytop)
histPlot.set_xticks(xedges)
histPlot.set_yticks(yedges)
histPlot.ticklabel_format(scilimits=(-3,2))
histPlot.tick_params(labelsize='small')
targetWidget.canvas.fig.tight_layout(pad=1, h_pad=None, w_pad=None, rect=(0,0,1,.95))
targetWidget.canvas.draw()
在mplwidget
与 Qt Designer 集成的文件中,我这样初始化画布:
self.fig = Figure(facecolor='white', edgecolor='gray', linewidth=1.0)
# initialization of the canvas
FigureCanvas.__init__(self, self.fig)
# we define the widget as expandable
FigureCanvas.setSizePolicy(self,
QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
# notify the system of updated policy
FigureCanvas.updateGeometry(self)
self.ax = self.fig.add_subplot(111, projection='3d')
如果有帮助,我可以发布已知良好的代码段,但我现在怀疑 bar3d 的一些已知错误正在表现出来 - 尽管我很想知道其他情况。
如果还有其他有用的代码,我会很乐意提供它们,但我不确定如何减少它,因为代码在独立状态下完全正常运行,并且仅在与 Qt 集成时显示问题 -这很难简洁地捕捉。