@@ -364,9 +364,41 @@ def isinteractive():
364364 return matplotlib .is_interactive ()
365365
366366
367+ class _ioff ():
368+ def __call__ (self ):
369+ matplotlib .interactive (False )
370+ uninstall_repl_displayhook ()
371+
372+ def __enter__ (self ):
373+ self .wasinteractive = isinteractive ()
374+ self .__call__ ()
375+
376+ def __exit__ (self , exc_type , exc_value , traceback ):
377+ if self .wasinteractive :
378+ matplotlib .interactive (True )
379+ install_repl_displayhook ()
380+ del self .wasinteractive
381+
382+
383+ class _ion ():
384+ def __call__ (self ):
385+ matplotlib .interactive (True )
386+ install_repl_displayhook ()
387+
388+ def __enter__ (self ):
389+ self .wasinteractive = isinteractive ()
390+ self .__call__ ()
391+
392+ def __exit__ (self , exc_type , exc_value , traceback ):
393+ if not self .wasinteractive :
394+ matplotlib .interactive (False )
395+ uninstall_repl_displayhook ()
396+ del self .wasinteractive
397+
398+
367399def ioff ():
368400 """
369- Turn the interactive mode off.
401+ Turn interactive mode off.
370402
371403 See Also
372404 --------
@@ -375,25 +407,54 @@ def ioff():
375407
376408 show : show windows (and maybe block)
377409 pause : show windows, run GUI event loop, and block for a time
410+
411+ Notes
412+ -----
413+ If you want the effects of this function to be temporary, it can
414+ be used as a context manager, for example::
415+
416+ with plt.ioff():
417+ # interactive mode will be off
418+ # figures will not automatically be shown
419+ fig1 = plt.figure()
420+ # ...
421+
422+ # This figure will be shown immediately
423+ fig2 = plt.figure()
378424 """
379- matplotlib .interactive (False )
380- uninstall_repl_displayhook ()
425+ return _ioff ()
381426
382427
383428def ion ():
384429 """
385- Turn the interactive mode on.
430+ Turn interactive mode on.
386431
387432 See Also
388433 --------
389- ioff : disable interactive mode
434+ ion : enable interactive mode
390435 isinteractive : query current state
391436
392437 show : show windows (and maybe block)
393438 pause : show windows, run GUI event loop, and block for a time
439+
440+ Notes
441+ -----
442+ If you want the effects of this function to be temporary, it can
443+ be used as a context manager, for example::
444+
445+ # if interactive mode is off
446+ # then figures will not be shown on creation
447+ plt.ioff()
448+ # This figure will not be shown immediately
449+ fig2 = plt.figure()
450+
451+ with plt.ion():
452+ # interactive mode will be on
453+ # figures will automatically be shown
454+ fig1 = plt.figure()
455+ # ...
394456 """
395- matplotlib .interactive (True )
396- install_repl_displayhook ()
457+ return _ion ()
397458
398459
399460def pause (interval ):
0 commit comments