【问题标题】:How to avoid importing pyplot in embedded qt4 GUI?如何避免在嵌入式 qt4 GUI 中导入 pyplot?
【发布时间】:2016-11-08 00:24:42
【问题描述】:

“根据这个SO note,嵌入时不应该导入pyplot。它会做一些时髦的事情,比如用自己的主循环运行自己的GUI。”

如果是这样,如何在不调用 plt.axes() 的情况下传递 Slider 所需的 matplotlib.axes._axes.Axes 参数? 在 GUI based on matplotlib documentation 中,我们[添加了以下内容以包含滑块]:

 def compute_initial_figure(self):
        ymax = 300
        window_size=1
        res= 0.1
        ax= self.axes
        t = np.arange(0.0, 100.0, 0.1)
        s = np.sin(2*np.pi*t)
        ax.plot(t, s)
        ax.axis([0, window_size, -ymax, ymax])
        ax.get_xaxis().get_major_formatter().set_useOffset(False)
        axcolor = 'lightgoldenrodyellow'
        axpos = plt.axes([.1, .1, 0.75, 0.05], axisbg=axcolor) #MAKES OWN FIG!
        spos = Slider(axpos, 'Time', res, t[-1], valinit=0)
        spos.on_changed(update)

axpos 行使用 plt 并创建自己的图形,与 Qt 窗口分开。注意 plt.axes 返回一个 matplotlib.axes._axes.Axes 对象而不是 matplotlib.axes._subplots.AxesSubplot 对象。

类似问题:
When matplotlib is embedded in PyQt4 how are axes/subplots labelled without using pyplot?
Combining PyQt and Matplotlib

【问题讨论】:

标签: python-2.7 matplotlib pyqt4


【解决方案1】:

plt.axes 函数通过获取当前图形然后调用 figure.add_axes 将坐标区添加到当前图形。在创建它时,您必须保留对该图的引用,而不是获取当前图。如果您查看http://matplotlib.org/examples/user_interfaces/embedding_in_qt4.html,您可以看到应该如何创建图形。我会以这个例子为起点。

因此,为了保持对图的引用,请将相关行更改为:

self.fig = Figure(figsize=(width, height), dpi=dpi)

然后像这样调用 add_axes 方法:

axpos = self.fig.add_axes([.1, .1, 0.75, 0.05], axisbg=axcolor)

【讨论】:

  • 感谢您的回复。似乎 fig.axes 是 TYPE: 而不是 matplotlib.axes._axes.Axes 所以它产生一个 TypeError: 'list' object is not callable。还在努力。
  • 啊,我看起来不太对。再次查看pyplot.axes 的来源,我看到它在当前图上调用add_axes。我将在上面更新我的帖子。
  • 完美。谢谢你。此外,对于滑块的目的: 1) 它希望在 compute_initial_figure() 之前定义画布 (self.canvas= FigureCanvas.__init__(self, fig))。 2) 同样,在示例中,该图定义为 fig 但我将其更改为 sel.fig 以方便以后使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-05
  • 2011-01-03
  • 1970-01-01
  • 2021-03-14
  • 2015-10-29
  • 1970-01-01
相关资源
最近更新 更多