无法在matplotlib中获取画布来绘制无花果

时间:2012-03-08 02:45:58

标签: python numpy matplotlib pyqt

根据我对使用matplotlib的基本了解,您将所需的plt存储在某些'fig'中,然后您可以使用canvas.draw()操作绘制所说的'fig'。如果是这种情况,那么我不应该有任何问题但是因为我做了,究竟是怎么回事以及在画布上得到一些东西的逻辑是什么。此外,我的最终目标是在QtPy窗口中显示此图。到目前为止的结果是我可以显示窗口和画布,但画布显示为空。我一直在关注http://matplotlib.sourceforge.net/users/artists.html并且觉得我正在做的事情并非完全错误,但也许我忽视了一些细微差别。这是我引用的代码:

def drawThis(self):

        self.axes.clear()
        self.axes.grid(self.grid_cb.isChecked())
        self.fig = plt.figure(figsize=(11,7),dpi=self.dpi)
        file = fileList[selFile]
        valid = [sColumn]
        matrix = np.loadtxt(file, skiprows=1, usecols=valid)
        colCount = np.loadtxt(file, dtype=object)
        totalCols = colCount.shape[1]

        kdeData = np.array(matrix)
        dataRange = (Decimal(max(abs(kdeData))) / 10).quantize(1, rounding=ROUND_UP) * 10

        gkde = stats.gaussian_kde(kdeData)
        ind = np.linspace(-int(dataRange), int(dataRange), len(kdeData) * sSamples)
        kdepdf = gkde.evaluate(ind)

        ##plot histogram of sample
        plt.hist(kdeData, len(kdeData), normed=1, alpha=0.20)
        ##plot data generating density
        plt.plot(ind, stats.norm.pdf(ind), 'r', linewidth=0.8, label='DGP normal')
        ##plot estimated density
        plt.plot(ind, kdepdf, 'g', linewidth=0.8, label='kde')
        plt.title('KDE for '+ str(nameList[selFile]))
        plt.legend()

        self.fig.canvas.draw()

1 个答案:

答案 0 :(得分:2)

我对matplotlib没有任何经验,但在查看您的代码时,我想知道您对pyplot的使用是否正确?你的代码看我的方式是,你使用pyplot来生成数据(你没有保留返回值),然后你绘制它,但我认为它实际上并没有在你的轴实例上运行。

我在这里可以找到如何使用matplotlib的示例:Segfault using matplotlib with PyQt ..他实际上是直接创建PyQt4 FigureCanvas并直接绘制到他的轴实例。

似乎pyplot.plot()方法可以使用数字和轴参数来告诉它使用哪个实例。我想知道它是否不使用你的轴,因为我在你的例子中看不到你如何创建轴本身。看看docs here

我猜你可能会尝试做这样的事情:

plt.plot(ind, kdepdf, 'g', axis=self.axis, linewidth=0.8, label='kde')

或者,也许可以使用self.axis确认您有创建self.axis = plt.axis(),或者甚至尝试直接使用轴实例进行所有绘图?