Description
Problem
Jupyter Qt Console, Spyder and probably Jupyter Notebooks and others can display enriched formats for objects.
It would be convenient if Figure
(and possibly other Artists where possible) returned these.
Note that this is different from %matplotlib inline
in the sense that the object returns its own representation, not that it plots inline. Although from some perspective it is the same thing. However, I'd like to be able to do something like
fig, ax = plt.subplots()
...
fig
and then fig
is shown inline.
And to be even more specific. I have a class where I would like to be able to return different "views" of it in this way. The class already have a _repr_svg_
-method (which returns an SVG generated from Matplotlib), but I would like to have properties that returns an object with a different _repr_svg_
. One way is to use a simple wrapper, similar to:
https://stackoverflow.com/questions/72613209/displaying-a-matplotlib-figure-from-a-custom-class-in-jupyter-notebook (although a bit more code is required), but maybe we would like to support this directly?
Related to #16782
Proposed solution
Add _repr_svg_
, _repr_png_
, and maybe some more methods (possibly _repr_mimebundle_
). The main question is when these are called and if it brings any performance penalties for people not relying on this?
Something like this will do:
def _repr_svg_(self):
buffer = io.StringIO()
self.savefig(buffer, format="svg")
return buffer.getvalue()
but this should be discussed before any PR is created.
There are a few methods like this already. Colors can draw themselves and I now see that there is a _repr_html_
for Figure
. As well as something for a font entry.