【问题标题】:How to show matplotlib plot from a figure object如何从图形对象显示 matplotlib 图
【发布时间】:2016-12-05 01:12:54
【问题描述】:

我的代码包含以下几行:

from matplotlib.figure import Figure

figure = Figure(figsize=(10, 5), dpi=dpi)

我怎样才能让 matplotlib 显示这个数字?我还展示了它嵌入在 tkinter 中,效果很好。但是我也可以在标准的 matplotlib 窗口中显示它。但我这辈子都无法让它发挥作用。

【问题讨论】:

  • 是的,我试过figure.show(),但这并没有成功。你是什​​么意思使用pyplot?我想我需要 Figure 稍后在 tkinter 中使用FigureCanvasTkAgg(figure, master=self)。示例here 均使用 matplotlib.figure。
  • 你的运行环境是什么?操作系统?命令行或任何 IDE?
  • 操作系统:macOS Sierra。我使用 python 3 在命令行(终端)中运行它。

标签: python matplotlib


【解决方案1】:

根据AttributeError while trying to load the pickled matplotlib figure,一个简单的解决方法是:

fig = plt.Figure(...)
......
managed_fig = plt.figure(...)
canvas_manager = managed_fig.canvas.manager
canvas_manager.canvas.figure = fig
fig.set_canvas(canvas_manager.canvas)

请注意,我在我的环境中遇到了“'Figure' object has no attribute '_original_dpi'”。不确定我的 PyPlot 和 PyQt5 之间是否存在兼容性问题。刚刚做了一个hack:

fig._original_dpi = 60

解决这个问题。不知道有没有更好的解决方案。

【讨论】:

    【解决方案2】:

    我通常使用 matplotlib 的 pyplot 进行即时生成(或在 jupyter 笔记本中生成图像)。如下所示:

    import matplotlib.pyplot as plt
    
    figure = plt.figure(figsize=(10, 5), dpi=dpi)
    plt.show()
    

    这会根据需要显示(空白)图形。

    【讨论】:

    • 使用plt.figure 而不是Figure 似乎确实有效。但是,当我绘图时,我还会得到另一个弹出窗口,其中包含一个带有颜色条的 matplotlib 图,如 here 所示。当我在 tkinter 中绘图时,然后决定使用plt.show() 进行绘图,它显示绘图 2 次,以及颜色条绘图 2 次。 (当我在 tkinter 中绘制 2 次时,没有它显示 3 次,等等)
    • @J.. 我不知道你在做什么的细节。我只能回答你在问题中提出的问题。如果您有不同的问题或用例,那么您应该问另一个问题,其中包含您所追求的确切内容。
    • 那我会试着弄清楚。如果我不能,我会提出另一个问题。感谢您的帮助!
    猜你喜欢
    • 2015-03-21
    • 2021-09-17
    • 1970-01-01
    • 2017-12-25
    • 2021-07-04
    • 2012-01-24
    • 2021-11-24
    • 1970-01-01
    相关资源
    最近更新 更多