You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Add _repr_html_ for inline backend to eliminate need for %matplotlib inline #16782
When launching a jupyter notebook, the environment variable MPLBACKEND is set to inline, but figures will still not be displayed in the output unless %matplotlib inline or import matplotlib.pyplot is run. Both of these commands hook IPython to a function that gets triggered whenever a Figure is the output from a cell. This function is responsible for printing the figure to the screen.
Proposed solution:
A _repr_html_ method exists for figures, but is only implemented for webagg backends. Something like the following could be added to _repr_html_.
Adding a _repr_html_ will not replace the figure life cycle management that inline currently does. Every other backend makes use of the global state in pyplot to allow you to build up figures over multiple cells (like you would in a desktop context), however inline destroys the Figure instance on show. This means you can not build up figures over multiple cells, but it does mean each cell is fully independent and you can get away with only using plt.* (because at the top of the cell there is never a "current figure").
What does this mean for this ticket? Would we change the behavior of inline wrt. life cycle management? If not is there a benefit of _repr_html_ compared to the current state?
I think that we need someone with good understanding of jupyter and its repr model to answer that.
I could see a path where having a _repr_html_ (or widget etc) that replaces the current show logic that grabs a display area inserts the figure into it. Some of this discussion may be best done in ipympl (as they own the widget version of the backend). Not sure how @SylvainCorlay feels about this, but it may make sense to move the static inline backend there as well (as the key thing really is the jupyter integration)?
IPython and Jupyter Notebook and JupyterLab call IPython.display.display(last_expression_in_input_cell)) for every input cell. IPython.display.display(obj) tries a bunch of obj._repr_*_() methods as appropriate for the given output format (e.g. html, latex, markdown, pretty (str)) and tries obj.__repr__() or obj.__str__() last (which is what the CPython REPL always calls to display non-assignment expressions).
This issue has been marked "inactive" because it has been 365 days since the last comment. If this issue is still present in recent Matplotlib releases, or the feature request is still wanted, please leave a comment and this label will be removed. If there are no updates in another 30 days, this issue will be automatically closed, but you are free to re-open or create a new issue if needed. We value issue reports, and this procedure is meant to help us resurface and prioritize issues that have not been addressed yet, not make them disappear. Thanks for your help!
I believe _repr_html_ is not helpful for the inline context. To use _repr_html_, the last return value of a cell would need to be a Figure object. For any reasonable code, that is not automatically the case. Thus, one would have to append an explict fig statement:
fig = plt.figure
[...] # plot code
fig
but that's basically equivalent to a show() call, and doesn't justify a new way:
This has always been confusing to me;
maybe because of the implicit matplotlib.pyplot.show().
More explicit would be to call display() when yielding output, which is what is implicitly called with the last expression of an input cell:
fig=plt.figure
[...] # plot codedisplay(fig)
This is more like the "print() to print output" style.
This is more understandable when there are other print() and display() calls in the same cell:
There could also or instead be a per-cell %%matplotlib cell magic.
That's how ipytest works. An example use case with %%ipytest and matplotlib:
%%ipytestfrommatplotlib.pyplotimportpltdeftest_thing1():
data=range(10)
df=pd.DataFrame(dict(x=data))
print(1, data)
display(2, 'two')
display(3)
df.plot(legend=True)
# plt.show() # display(plt)# -> cell_output[n]['text/html'] = plt._repr_html_()display(4, data)
assertbool(plt)
#test_thing1() # ipytest automatically calls this (after preprocessing lines with assert keywords) because it starts with test_
But then there would need to be multiple IPython cell magics though;
multiple cell magics would be overly verbose and less usable
when display(plt) could call plt._repr_html_() which could just call plt.show()?:
What people typically do, FWIU:
%matplotlibinline# import matplotlib.pyplot as plt
Because of the %matplotlib inline IPython line magic and/or import matplotlib.pyplot as plt python import statement, df.plot(legend=True) results in a non-interactive image of matplotlib cell output
that is saved in the .ipynb file
so that users can review the cached output without [re-]running the notebook themselves,
and so that there is a static .png/.jpg for jupyter-nbconvert --to latex or --to pdf.
TODO: run this code; is matplotlib output displayed when the tests are run (and stdout is captured and thus hidden by pytest if the test doesn't fail)
Activity
tacaswell commentedon Mar 30, 2021
Adding a
_repr_html_will not replace the figure life cycle management that inline currently does. Every other backend makes use of the global state in pyplot to allow you to build up figures over multiple cells (like you would in a desktop context), however inline destroys theFigureinstance on show. This means you can not build up figures over multiple cells, but it does mean each cell is fully independent and you can get away with only usingplt.*(because at the top of the cell there is never a "current figure").timhoffm commentedon Mar 30, 2021
What does this mean for this ticket? Would we change the behavior of inline wrt. life cycle management? If not is there a benefit of
_repr_html_compared to the current state?tacaswell commentedon Mar 30, 2021
I think that we need someone with good understanding of jupyter and its repr model to answer that.
I could see a path where having a
_repr_html_(or widget etc) that replaces the currentshowlogic that grabs a display area inserts the figure into it. Some of this discussion may be best done in ipympl (as they own the widget version of the backend). Not sure how @SylvainCorlay feels about this, but it may make sense to move the static inline backend there as well (as the key thing really is the jupyter integration)?westurner commentedon Mar 31, 2021
Jupyter internals info from https://news.ycombinator.com/item?id=25923123 re: xeus-cling (c++ kernel) and widgets:
IPython and Jupyter Notebook and JupyterLab call
IPython.display.display(last_expression_in_input_cell))for every input cell.IPython.display.display(obj)tries a bunch ofobj._repr_*_()methods as appropriate for the given output format (e.g. html, latex, markdown, pretty (str)) and triesobj.__repr__()orobj.__str__()last (which is what the CPython REPL always calls to display non-assignment expressions).ipympl https://github.com/matplotlib/ipympl/blob/master/ipympl/backend_nbagg.py is built atop ipywidgets: https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20List.html
github-actions commentedon Jul 12, 2023
This issue has been marked "inactive" because it has been 365 days since the last comment. If this issue is still present in recent Matplotlib releases, or the feature request is still wanted, please leave a comment and this label will be removed. If there are no updates in another 30 days, this issue will be automatically closed, but you are free to re-open or create a new issue if needed. We value issue reports, and this procedure is meant to help us resurface and prioritize issues that have not been addressed yet, not make them disappear. Thanks for your help!
timhoffm commentedon Jul 12, 2023
I believe
_repr_html_is not helpful for the inline context. To use_repr_html_, the last return value of a cell would need to be a Figure object. For any reasonable code, that is not automatically the case. Thus, one would have to append an explictfigstatement:but that's basically equivalent to a
show()call, and doesn't justify a new way:Thus, closing as not planned.
westurner commentedon May 15, 2024
This has always been confusing to me;
maybe because of the implicit
matplotlib.pyplot.show().More explicit would be to call
display()when yielding output, which is what is implicitly called with the last expression of an input cell:print()to print output" style.display(fig)get run in this (pandas+matplotlib) code (when there is no explicitglobal plt.show())?%matplotlib inlineorimport matplotlib.pyplotin a Jupyter notebook, it will:tacaswell commentedon May 15, 2024
@westurner https://github.com/matplotlib/mpl-gui may also be of interest to you as might matplotlib/ipympl#171
westurner commentedon May 15, 2024
matplotlib.pyplot.ion()(plt.ion()) mentionsmatplotlib/lib/matplotlib/pyplot.py
Lines 696 to 699 in 80b08bd
If those can already occur anywhere in a notebook,
couldn't we also have / why can't we also just,
in
matplotlib.pyplot?:So that this works, and is explicit about when it is display()'ing or printing output:
westurner commentedon May 15, 2024
There could also or instead be a per-cell
%%matplotlibcell magic.That's how ipytest works. An example use case with
%%ipytestandmatplotlib:But then there would need to be multiple IPython cell magics though;
multiple cell magics would be overly verbose and less usable
when
display(plt)could callplt._repr_html_()which could just callplt.show()?:What people typically do, FWIU:
%matplotlib inlineIPython line magic and/orimport matplotlib.pyplot as pltpython import statement,df.plot(legend=True)results in a non-interactive image of matplotlib cell outputthat is saved in the
.ipynbfileso that users can review the cached output without [re-]running the notebook themselves,
and so that there is a static .png/.jpg for
jupyter-nbconvert --to latexor--to pdf.