matplotlib:如何创建原始后端



以下程序不适用于非GUI环境。 我想让这个程序在调用plt.show时将图形保存到临时 png 文件中。

import matplotlib.pyplot as plt
plt.scatter(2,3)
plt.scatter(4,5)
plt.show()

我知道这可以通过使用plt.savefig而不是plt.show来解决(参见将绘图保存到图像文件而不是使用 Matplotlib 显示它(。但我不想改变程序本身。该程序可能由可能熟悉在GUI环境中使用matplotlib的其他用户提供。

所以我考虑将 matplotlib 的后端更改为我自己的后端,从而改变show的行为。可以通过更改matplotlibrc来完成。 但是关于后端的文档只解释了如何选择"内置"后端: https://matplotlib.org/faq/usage_faq.html?highlight=backend#coding-styles

文档说后端可以指定为module://my_backend,但它没有定义my_backend的"接口"(应该用哪些名称实现什么样的类/对象?

是否有任何文档可以解释后端的接口?(或者show的其他一些解决方法更改行为?

最小的后端可能如下所示,我们只需从 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()

不幸的是,我不得不创建一个单独的答案,但这实际上是对已接受答案的补充。您还需要创建一个FigureManager,否则如果您尝试show()plt.fig(),您将获得一个神秘的UserWarning: Matplotlib is currently using module://mybackend, which is a non-GUI backend, so cannot show the figure.。到目前为止,我的额外代码是这样的:

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

您还询问是否有任何文档可以解释后端接口。

有:matplotlib源代码中有一个名为"template"的后端,带有描述接口的注释。

https://github.com/matplotlib/matplotlib/blob/main/lib/matplotlib/backends/backend_template.py

最新更新