【问题标题】:Matplotlib Qt4 GUI programming - replace plt.figure() with OO equivalentMatplotlib Qt4 GUI 编程 - 将 plt.figure() 替换为 OO 等效项
【发布时间】:2016-12-06 02:06:49
【问题描述】:

我有一个使用 Qt4 Designer 制作的应用程序,它将 matplotlib 图形插入到容器小部件中。

生成图形的代码来自另一个模块,obspy:

self.st.plot(fig = self.rawDataPlot)

https://docs.obspy.org/packages/autogen/obspy.core.stream.Stream.plot.html 通常,这将为st 对象的数据创建并显示一个matplotlib 图,这是时间序列。当指定 fig 参数时,这会告诉 self.st.plot 绘制到现有的 matplotlib 图形实例。

我必须生成图形然后将其放置在我的 GUI 小部件中的代码是:

def addmpl(self, fig, layout, window):  # code to add mpl figure to Qt4 widget
    self.canvas = FigureCanvas(fig)
    layout.addWidget(self.canvas)
    self.canvas.draw()
    self.toolbar = NavigationToolbar(self.canvas, 
    window, coordinates=True)
    layout.addWidget(self.toolbar)

self.rawDataPlot = plt.figure()     # code to create a mpl figure instance  
self.st.plot(fig = self.rawDataPlot)  # plot time-series data to existing matplotlib figure instance
self.addmpl(self.rawDataPlot, self.mplvl, self.mplwindow)  # add mpl figure to Qt4 widget

我想要做的是实例化一个 matplot 图形(供self.st.plot 使用),但要避免使用plt.figure(),因为我已经读到使用面向对象编程时这是一种不好的做法。

如果我将 plt.figure() 替换为 Figure()(来自 matplotlib.figure.Figure()),则会出现错误:

AttributeError: 'NoneType' object has no attribute 'draw'

就目前而言,如果我使用 plt.figure(),应用程序运行良好,但有没有一种干净的方法可以避免使用 is,甚至对于我的情况是否有必要?

PS,这里的代码 sn-ps 取自更大的来源,但我认为它明白了这一点..

【问题讨论】:

    标签: python-2.7 matplotlib qt4


    【解决方案1】:

    原则上这两种方法都应该有效。 假设导入是正确的,您是否设置 self.rawDataPlot = plt.figure()self.rawDataPlot = Figure() 并没有太大的区别。

    所以错误很可能是在self.st.plot() 函数中触发的。 (一般情况下,如果您报告错误,请附加回溯。)

    obspy.core.stream.Stream.plot的出处有关键字参数

    :param draw: 如果为 True,则图形画布显式重新绘制,这 确保现有数字是新鲜的。没有什么不同的 对于尚不可见的数字。 默认为True

    这意味着显然 plot 函数试图绘制画布,在提供 Figure() 的情况下尚未设置。

    因此,一个很好的猜测是调用

    self.rawDataPlot = Figure()
    self.st.plot(fig = self.rawDataPlot, draw=False)
    

    看看问题是否仍然存在。

    【讨论】:

    • 我还发现了另一种无需调用 plt.figure() 的方法:self.rawDataPlot = self.st.plot(fig = None, handle = True)。在self.st.plot() 中设置handle = True 会返回matplotlib 图形实例,而不是像fig = something... 那样要求已经存在一个图形实例
    猜你喜欢
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    • 2017-12-12
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    相关资源
    最近更新 更多