首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >对mpl.figure.Figure的列表引用不显示情节

对mpl.figure.Figure的列表引用不显示情节
EN

Stack Overflow用户
提问于 2019-07-30 14:02:33
回答 1查看 105关注 0票数 1

我试图用一个对象来处理一个数字列表。不幸的是,从一张数字清单中画出图似乎有问题。

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

代码语言:javascript
运行
复制
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()

结果(这是我想要的):

结果行未注释:

在其他一些测试中,我发现它可能与破坏对象有关。由于list是一个可变对象,这可能是连接。我还尝试了(失败的)几个变通方法来复制图形对象以进行绘图:我使用了类似于fig = myCopy(self.figs[0])pickle-copy的东西。

你能给我解释一下正在发生的事情以及什么是解决办法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-30 14:14:46

__init__中,将轴赋予self.fig,并绘制此Axes对象:

代码语言:javascript
运行
复制
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对象,因此它们基本上是空的。因此,你看到的是一个空洞的数字:

代码语言:javascript
运行
复制
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,以提高图形管理器的总体可用性:

代码语言:javascript
运行
复制
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)

然后,您可以实现我前面描述的工作流:

代码语言:javascript
运行
复制
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()
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57273569

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档