在PyQt中使用matplotlib Figure

1 投票
1 回答
4332 浏览
提问于 2025-04-17 21:04

我是一名编程新手。现在我想在PyQt4的图形界面中使用一个matplotlib的小部件。这个小部件类似于matplotlib在qt的示例

用户在某个时候需要点击图表,我本以为可以用ginput()来处理这个问题。但这并不奏效,因为这个图形没有管理器(见下文)。请注意,这个问题和另一个问题很相似,但那个问题一直没有得到解答。

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非常流行(我几乎找不到没有它的答案),但在使用图形界面时似乎不太好用。我原以为pyplot只是面向对象框架的一个包装,但看来我还是个新手。

那么我的问题是: 有没有办法把pyplot和一个matplotlib.figure.Figure实例连接起来? 有没有简单的方法可以给一个Figure添加管理器?我在matplotlib.backends.backend_qt4agg中找到了new_figure_manager(),但即使它是正确的解决方案,我也没能让它工作。

非常感谢,

詹姆斯

1 个回答

2

pyplot 其实是一个面向对象接口的封装,它为你做了很多事情。你可以再仔细看看你链接的例子,

FigureCanvas.__init__(self, fig)

那一行非常重要,因为它告诉图形使用哪个画布。Figure 对象就是一组 Axes 对象(还有一些 Text 对象),而 canvas 对象则知道如何把 Artist 对象(也就是 matplotlib 内部用来表示线条、文本、点等的方式)转换成好看的颜色。此外,你可以看看我写的另一个嵌入示例,它没有子类化 FigureCanvas

还有一个PR,目的是让这个过程更简单,但现在因为我们在忙着发布 1.4 版本,这个进展有点停滞。

另外可以看看:推荐使用 matplotlib 还是 pylab 来绘图?如何将 pyplot 函数附加到图形实例上?

撰写回答