question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

add context manager capabilities to ioff when using ipympl

See original GitHub issue

Often when I’m using the widget backend in jupyterlab and want to do something like define a small layout of ipywidgets and plots I find myself using this pattern:

plt.ioff()
fig = plt.figure()
#... other things I don't want to be interactive
plt.ion()
....
widgets.VBox([slider1,slider2,fig.canvas])
  1. It took me quite a while to figure out that I needed to use ioff and ion to prevent multiple views of the figure showing up. It would be great if more discussion of this was included in the documentation (https://github.com/matplotlib/ipympl/issues/208) and examples
  2. I like the idea of being able to use ioff as a context manager at least in the context of this backend. I propsed this on the matplotlib repo https://github.com/matplotlib/matplotlib/issues/17013 but that may not have been the right place for it as it would be useful primarily for this backend

Could this backend redefine iofflike so:

class ioff:
    def __call__(self):
        matplotlib.interactive(False)
        uninstall_repl_displayhook()
        
    def __enter__(self):
        self.call()
        
    def __exit__(self):
        ion()

I imagine this occuring in the ipympl __init__.py. This would enable the above example to be the slightly cleaner:

with plt.ioff:
   fig = plt.figure()
   #... other things I don't want to be interactive
widgets.VBox([slider1,slider2,fig.canvas])

Another issue where the usage of ioff/ion came up is: https://github.com/matplotlib/ipympl/issues/203 though there was no discussion of the context manager there.

Currently I just always import pyplot as plt and just redefine plt.ioff to be the above class which works fairly well.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:6 (4 by maintainers)

github_iconTop GitHub Comments

2reactions
ianhicommented, Aug 12, 2020

Context manager has now happened in matplotlib 🎉 !

I think it will be included in the 3.4 release. Usage will be:

with plt.ion():
     # ...
0reactions
ianhicommented, May 8, 2020

If I am understanding this right, the issue is that sometimes you want plt.figure() to make a stand-alone widget that get put on the screen and other times you want it to make the widget, but not display it because later you are going to manually pack it into a bigger layout?

Yup! I ran into this when working with XYZT stacks of microscopy images. I have several classes in python module that manage viewing these stacks and for things like per image manual segmentation (lasso selector) or cell labelling. Then these classes all have methods like:

    def __init__(self,arr):
        """
        inputs
        --------
        arr : structured array
             with attributes, 'pos', 'time', 'z', 'name', 'image (X,Y)' 
        """
        ....
        # boring initialization stuff
        plt.ioff()
        self.fig = plt.figure()
        plt.ion()
        self.ax = plt.gca()

        self.displayed = self.ax.imshow(self.arr['image'][self.t_idx][0])
        # boring initialization + defining some control sliders

    # other functions

    def _ipython_display_(self):
        display(widgets.VBox([self.z_slider,self.t_slider,self.fig.canvas]))

There is actually already a kind of “context manager” that you should be using instead of the plt.ion/ioff

I don’t think that the output widget is the best way to solve my problem. It certainly works, but I’d prefer for no output to be generated when creating my object rather than to have to capture extraneous output. My bad on not posting an example of my actual use case.

Though, this is great to know about for the original example I posted which I definitely run into when playing around with things in the notebook. It’s also interesting to thing about throwing these into a sidecar output.

Why is it preferred to use the output rather than suppress the output? It seems like this makes it more difficult to manipulate the canvas position with various widget layout tools.

I’ve been asked to do this previously but haven’t quite finished a first draft of it.

If you want feedback on a draft I’d be happy to provide some, my learning of all this is fresh enough that I’ll bet I remain capable of wildly misinterpreting documentation so I could be a stress test for it…

Read more comments on GitHub >

github_iconTop Results From Across the Web

API — mpl-interactions 0.6.1 documentation
When using the ipympl backend these functions will leverage ipywidgets for the controls, ... A context manager for turning interactive mode off.
Read more >
Comprehensive Example — ipympl - Matplotlib
Testing matplotlib interactions with a simple plot fig = plt.figure() ... usage of ioff as a context manager, see the ipympl issue and...
Read more >
Context Managers and Python's with Statement
In this step-by-step tutorial, you'll learn what the Python with statement is and how to use it with existing context managers.
Read more >
mpl-interactions - PyPI
ioff as a context manager. from mpl_interactions.utils import ioff with ioff: # interactive mode will be off fig = plt.figure() # other ...
Read more >
Python With: Using and Writing Context Managers in Python
Of course, you can use the features when you need them on Python classes ... create “context managers” (classes that can be used...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found