matplotlib:如何创建原始后端

5
以下程序无法在非GUI环境下工作。 我希望让这个程序在调用plt.show时将图形保存到一个临时的png文件中。
import matplotlib.pyplot as plt
plt.scatter(2,3)
plt.scatter(4,5)
plt.show()

我知道可以使用plt.savefig代替plt.show来解决这个问题(参见Save plot to image file instead of displaying it using Matplotlib)。但我不想改变程序本身。该程序可能由其他熟悉在GUI环境中使用Matplotlib的用户提供。
因此,我考虑将Matplotlib的后端更改为自己的后端,以更改show的行为。这可以通过更改matplotlibrc来完成。 但是关于后端的文档只解释了如何选择“内置”后端:https://matplotlib.org/faq/usage_faq.html?highlight=backend#coding-styles 文档说,后端可以指定为module://my_backend,但它没有定义my_backend的“接口”(应该在哪些名称中实现哪些类型的类/对象?)
是否有任何解释后端接口的文档?(还是其他绕过更改show行为的方法?)
3个回答

4
最简单的后端看起来可能像这样,我们只需从agg后端获取图形画布(因此能够使用所有相关方法)。
from matplotlib.backend_bases import Gcf
from matplotlib.backends.backend_agg import FigureCanvasAgg

FigureCanvas = FigureCanvasAgg

def show(*args, **kwargs):
    for num, figmanager in enumerate(Gcf.get_all_fig_managers()):
        figmanager.canvas.figure.savefig(f"figure_{num}.png")

假设您将其保存为 mybackend.py ,您可以通过 matplotlib.use(“module://mybackend”)将其用作后端。
import matplotlib
matplotlib.use("module://mybackend")
import matplotlib.pyplot as plt

plt.figure()
plt.plot([1,3,2])

plt.figure()
plt.scatter([1,2,3], [3,2,3], color="crimson")

plt.show()

这正是我需要的,但它并不总是有效。这个可以工作:plt.plot([1,2,3],[2,1,4]); plt.show(),但这个不行:fig = plt.figure(); fig.gca().plot([1,2,3],[3,3,1]); fig.show()。我得到了以下警告信息:UserWarning: Matplotlib is currently using module://pyptex, which is a non-GUI backend, so cannot show the figure. 这显然来自于 FigureManagerBase.show()。有没有快速修复的方法? - Sébastien Loisel
啊,看起来你应该制作一个自定义的FigureManager。不过我无法在这个评论中粘贴代码... - Sébastien Loisel

1

1

很不幸,我需要创建一个单独的答案,但这实际上是已接受的答案的补充。您还需要创建一个FigureManager,否则,如果您尝试show() plt.fig(),则会得到一个难以理解的UserWarning:Matplotlib目前正在使用module://mybackend,这是一个非GUI后端,因此无法显示图形。。到目前为止,我的额外代码如下:

from matplotlib.backend_bases import FigureManagerBase

class FigureManager(FigureManagerBase):
    def show(self):
        self.canvas.figure.savefig('foo.png')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接