1

I am developing a library and a function is receiving (from another library) a figure created using the Figure class from matplotlib.figure and I would like to display it.

I know how to display it using a specific backend (like the Tk backend in How to display a matplotlib figure created directly from Figure class?) or the various "embed in a GUI" examples at https://matplotlib.org/stable/gallery/index.html#embedding-matplotlib-in-graphical-user-interfaces but I want to do it in a backend-agnostic way. In other words, I would like to use whatever backend is the default in the user config.

import matplotlib
fig = matplotlib.figure.Figure()
ax = fig.add_subplot()
ax.plot([1, 3, 2])
fig.show()   # <--- this does not work

I have had a partial success with this code:

import matplotlib.pyplot as plt

mgr = plt._backend_mod.new_figure_manager_given_figure(1, fig)
mgr.show()

But this seems hacky (using the "protected" _backend_mod attribute) and it does not seem to start a GUI event loop so it only works if I happen to have a GUI corresponding to that backend already running, for example if I am within a jupyter Qt console.

But is there a way to make this work for a standalone program too?

0 Answers0