首页 > 解决方案 > 对 mpl.figure.Figure 的列表引用不显示绘图

问题描述

我正在尝试处理带有对象的数字列表。不幸的是,从数字列表中绘制似乎存在问题。

请在下面的示例中注释掉该行,您会看到绘图是如何中断的:

import matplotlib as mpl
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, FigureManagerQT


class Test:
    def __init__(self):
        self.figs = [mpl.figure.Figure(),mpl.figure.Figure()]
        self.fig = mpl.figure.Figure()
        ax = self.fig.subplots()
        ax.plot([1,2],[3,4])

    def show(self):
        fig = self.fig  # works
#        fig = self.figs[0]  # does not work
        canvas = FigureCanvasQTAgg(fig)
        figManager = FigureManagerQT(canvas, 0)

a=Test()
a.show()

结果(这就是我想要的): 在此处输入图像描述

未注释行的结果: 在此处输入图像描述

在其他一些测试中,我发现它可能与破坏对象有关。由于列表是可变对象,因此这可能是连接。我还尝试(不成功)几种解决方法来复制图形对象以进行绘图:我使用了类似于fig = myCopy(self.figs[0])pickle-copy组合的东西。

您能否解释一下正在发生的事情以及可能的解决方法?

标签: pythonmatplotlib

解决方案


__init__中,您将坐标轴指定给该对象self.fig并绘制到该Axes对象:

class Test:
    def __init__(self):
        self.figs = [mpl.figure.Figure(),mpl.figure.Figure()]
        self.fig = mpl.figure.Figure()
        ax = self.fig.subplots()
        ax.plot([1,2],[3,4])

中的图形对象self.figs没有Axes附加任何对象,因此它们基本上是空的。结果,你看到的是一个空图:

def show(self):
    fig = self.figs[0] # This is a figure with no axes
    canvas = FigureCanvasQTAgg(fig)
    figManager = FigureManagerQT(canvas, 0)

您的逻辑问题在于,在__init__方法中绘制数据并没有真正的意义。您的工作流程应该是:

  1. 初始化
  2. 图选择
  3. 阴谋
  4. 节目

我建议你添加两个方法,select_figureplot,以提高你的图形管理器的整体可用性:

class Test:
    def __init__(self):
        self.fig = None
        self.figures = [mpl.figure.Figure(), mpl.figure.Figure()]

    def select_figure(self, index):
        self.fig = self.figures[index]

    def plot(self, x, y):
        ax = self.fig.subplots()
        ax.plot(x, y)

    def show(self):
        canvas = FigureCanvasQTAgg(self.fig)
        figManager = FigureManagerQT(canvas, 0)

然后你可以实现我上面描述的工作流程:

test = Test()

test.select_figure(0)
test.plot([1, 2], [3, 4])
test.show()

test.select_figure(1)
test.plot([3, 4], [5, 6])
test.show()

推荐阅读