在figu中找不到Axes实例参数

2024-06-16 09:41:23 发布

您现在位置:Python中文网/ 问答频道 /正文

def plot(self, fig):
    ax = fig.gca()

当删除QtMatPlotLib小部件上的项时,将调用此plot函数。最后,.draw()将更新所有内容。出现的问题如下: 调用完成绘图的外部函数,ax必须是当前轴(fig/axis不作为参数传递)。因此我不得不补充

^{pr2}$

一切都很好。不知何故,可能是因为更新到python(x,y)2.7.5.1(mpl是1.3.1),我得到了这个错误Axes instance argument was not found in a figure.只是在这种情况下,当我想要这个外部函数(scipy dendrogram func)在预定义的轴上绘制。我试着跟着它

[Dbg]>>> fig
<matplotlib.figure.Figure object at 0x0A119A90>
[Dbg]>>> fig.gca()
<matplotlib.axes.AxesSubplot object at 0x0A119CD0>

然后进入子例程pyplot.sca(ax)

managers = _pylab_helpers.Gcf.get_all_fig_managers()
for m in managers:
    if ax in m.canvas.figure.axes:
        _pylab_helpers.Gcf.set_active(m)
        m.canvas.figure.sca(ax)
        return
raise ValueError("Axes instance argument was not found in a figure.")

名单似乎是空的

[Dbg]>>> managers
[]

也许你们有些人有个想法,可能是什么问题,尽管远程诊断可能很困难。在我想要的图/轴上绘制dendrogram图的另一种方法也很有用。在

还请给出一个提示,说明应该使用什么来更新绘图,因为MatplotlibWidgetfigure和{}有一个draw方法。在

编辑:试图创建MWE。难道没有人遇到同样的错误吗?或者谁能告诉我这里出了什么问题?在

import sys
from matplotlibwidget import MatplotlibWidget
from matplotlib import pyplot
from PyQt4.QtGui import QMainWindow, QApplication

import scipy.cluster.hierarchy as hac
import numpy as np

class ApplicationWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.mplwidget = MatplotlibWidget(self, title='Example',
                        xlabel='Observation', ylabel='Distance', hold=True)
        self.mplwidget.setFocus()
        self.setCentralWidget(self.mplwidget)

    def plotScree(self, Z, fig):
        ax = fig.gca()
        ax.plot(range(len(Z)), Z[::-1,2])

    def plot(self, Z, fig):
        ax = fig.gca()
        pyplot.sca(ax)
        hac.dendrogram(Z)

app = QApplication(sys.argv)
win = ApplicationWindow()

X = np.random.random(100).reshape(25, 4)
Z = hac.linkage(X)

#win.plotScree(Z, win.mplwidget.figure)
win.plot(Z, win.mplwidget.figure)

win.show()
sys.exit(app.exec_())

Tags: 函数inimportselfplotdeffigax
1条回答
网友
1楼 · 发布于 2024-06-16 09:41:23

Python(x,y)中matplotlibwidget的实现似乎被破坏了。在

我相信有问题的文件是this1。如果您将该文件的第67行改为self.figure = pypolt.figure(figsize=(width, height), dpi=dpi),那么您的代码将按您的需要工作。我已经包含了下面修改过的代码的完整副本,这样您就可以将其复制/粘贴到您的项目中,并使用matplotlibwidget,而不是从python(x,y)导入

问题似乎是直接实例化Figure对象会跳过整个Figure管理器构造的负载,这就是引发该错误的原因。我建议你用Python(x,y)提交一个bug报告并链接到这篇文章!在

带修改行的完整代码(请参阅上面的存储库链接以获取许可证)

from PyQt4.QtGui import QSizePolicy
from PyQt4.QtCore import QSize

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as Canvas
from matplotlib.figure import Figure

from matplotlib import rcParams
rcParams['font.size'] = 9
from matplotlib import pyplot

class MatplotlibWidget(Canvas):
    """
    MatplotlibWidget inherits PyQt4.QtGui.QWidget
    and matplotlib.backend_bases.FigureCanvasBase

    Options: option_name (default_value)
       -    
    parent (None): parent widget
    title (''): figure title
    xlabel (''): X-axis label
    ylabel (''): Y-axis label
    xlim (None): X-axis limits ([min, max])
    ylim (None): Y-axis limits ([min, max])
    xscale ('linear'): X-axis scale
    yscale ('linear'): Y-axis scale
    width (4): width in inches
    height (3): height in inches
    dpi (100): resolution in dpi
    hold (False): if False, figure will be cleared each time plot is called

    Widget attributes:
            -
    figure: instance of matplotlib.figure.Figure
    axes: figure axes

    Example:
       -
    self.widget = MatplotlibWidget(self, yscale='log', hold=True)
    from numpy import linspace
    x = linspace(-10, 10)
    self.widget.axes.plot(x, x**2)
    self.wdiget.axes.plot(x, x**3)
    """
    def __init__(self, parent=None, title='', xlabel='', ylabel='',
                 xlim=None, ylim=None, xscale='linear', yscale='linear',
                 width=4, height=3, dpi=100, hold=False):
        self.figure = pyplot.figure(figsize=(width, height), dpi=dpi)
        self.axes = self.figure.add_subplot(111)
        self.axes.set_title(title)
        self.axes.set_xlabel(xlabel)
        self.axes.set_ylabel(ylabel)
        if xscale is not None:
            self.axes.set_xscale(xscale)
        if yscale is not None:
            self.axes.set_yscale(yscale)
        if xlim is not None:
            self.axes.set_xlim(*xlim)
        if ylim is not None:
            self.axes.set_ylim(*ylim)
        self.axes.hold(hold)

        Canvas.__init__(self, self.figure)
        self.setParent(parent)

        Canvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)
        Canvas.updateGeometry(self)

    def sizeHint(self):
        w, h = self.get_width_height()
        return QSize(w, h)

    def minimumSizeHint(self):
        return QSize(10, 10)

相关问题 更多 >