python - 在图中找不到轴实例参数

标签 python matplotlib pyqt scipy

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

当在 Qt MatPlotLib 小部件上放置一个项目时,将调用此绘图函数。最后,所有内容都将由 .draw() 更新。发生的问题如下: 调用一个完成绘图的外部函数,ax 必须是当前轴(图/轴不作为参数传递。因此我不得不添加 p>

pyplot.sca(ax)

一切都很好。只是不知何故,可能是因为更新到 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
[]

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

还请提示应该使用什么来更新关于 MatplotlibWidget 的绘图,figureaxes 有一个 绘制方法。

编辑:试图创建一个 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_())

最佳答案

Python(x,y) 中 matplotlibwidget 的实现似乎已损坏。

我认为有问题的文件是 this一。如果将该文件的第 67 行更改为读取 self.figure = pypolt.figure(figsize=(width, height), dpi=dpi) 那么您的代码将按您的意愿工作。我在下面包含了修改后代码的完整副本,因此您只需将其复制/粘贴到您的项目中并使用该 matplotlibwidget 而不是从 python(x,y) 导入该代码

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

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

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)

关于python - 在图中找不到轴实例参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20562582/

相关文章:

python - Scipy Griddata 输出维度

python - 如何抑制 QWebEngineView 错误的控制台输出?

python - 如何在 Python 中使用 'requests' 成功登录 (GET/POST) - 409 冲突

python - 箱线图 X 值出现多次

Python:无法从字符串中删除换行符

python - Python Descriptors的具体实现

python - 将 SHAP 汇总图另存为 PDF/SVG

python - 如何解释 keras "predict_generator "输出?

python - Matplotlib timedelta64 索引作为 x 轴

python - 在 QMenu 中一次可检查一个 QAction