在PyQt中使用matplotlib图

时间:2014-03-06 06:52:18

标签: python matplotlib pyqt

这里编程菜鸟。我正在尝试在PyQt4 GUI中使用matplotlib小部件。小部件类似于matplotlib的example for qt

在某些时候,用户需要点击图,我认为像ginput()会处理。但是,这不起作用,因为该图没有经理(见下文)。请注意,这与another question非常相似,但从未得到回答。

AttributeError: 'NoneType' object has no attribute 'manager'
Figure.show works only for figures managed by pyplot, normally created by pyplot.figure().

我假设“通常”有一种解决方法。

另一个简单的演示脚本:

from __future__ import print_function

from matplotlib.figure import Figure
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 5, 0.1)
y = np.sin(x)
# figure creation by plt (also given a manager, although not explicitly)
plt.figure()
plt.plot(x,y)
coords = plt.ginput() # click on the axes somewhere; this works
print(coords)

# figure creation w/o plt
manualfig = Figure()
manualaxes = manualfig.add_subplot(111)
manualaxes.plot(x,y)
manualfig.show() # will fail because of no manager, yet shown as a method
manualcoords = manualfig.ginput() # comment out above and this fails too
print(manualcoords)

像pyplot一样受欢迎(没有它我很难找到答案),在使用GUI时它看起来并不好看。我认为pyplot只是OO框架的包装,但我想我只是一个菜鸟。

我的问题是: 有没有办法将pyplot附加到matplotlib.figure.Figure的实例? 有没有一种简单的方法将经理附加到图?我在matplotlib.backends.backend_qt4agg中找到了new_figure_manager(),但是无法使它工作,即使它是正确的解决方案。

非常感谢,

詹姆斯

1 个答案:

答案 0 :(得分:2)

pyplot只是OO界面的包装器,但它为你阅读你再次链接的例子做了很多工作,

FigureCanvas.__init__(self, fig)

行是非常重要的,因为这是告诉图形使用什么画布。 Figure对象只是Axes个对象(以及一些Text个对象)的集合,canvas对象知道如何转换Artist个对象(即matplotlib的线条,文本,点等的内部表示,以漂亮的颜色。另请参阅something I wrote了解另一个不归类FigureCanvas的嵌入示例。

有一个PR可以让这个过程变得更容易,但是当我们进入1.4时,它会停滞不前。

另见:Which is the recommended way to plot: matplotlib or pylab?How can I attach a pyplot function to a figure instance?