1

I want to create a function that would return a pyplot object but will not plot it out unless explicitly specified.

Following is a example function similar to what I'm trying to create.

import numpy as np
import matplotlib.pyplot as plt

def plot_it_now():
    A = np.linspace(0,10,10)
    B = np.exp(A)
    fig = plt.figure()
    plt.plot(A, label='linear sequence')
    plt.plot(B, label='exponential sequence')
    plt.xlabel('x-axis')
    plt.ylabel('y-axis')
    plt.legend(loc='best')

myplot = plot_it_now()

the problem is the moment I call this function into a variable it also plots it out. While that's the usual behaviour, I want to persist the pyplot object into a variable and it should plot it only when i call it. Something like this,

plt.figure(figsize=(5,5))
myplot = plot_it_now()
plt.show()
Aman Singh
  • 1,111
  • 3
  • 17
  • 31
  • `plot_it_now()` doesn't return any value so you have `myplot = None`. If you don't what to see plot then don't run `plot_it_now()`. `plot()` creates objects directly on figure and axis - and it may create many separated objects (if you plot dots or bars). – furas Sep 23 '22 at 11:28
  • maybe you need `set_visible` [python - How to toggle visibility of matplotlib figures? - Stack Overflow](https://stackoverflow.com/questions/28463479/how-to-toggle-visibility-of-matplotlib-figures) – furas Sep 23 '22 at 11:34

1 Answers1

1

matplotlib has an interactive mode.

To check its state :

import matplotlib as mpl

print(mpl.is_interactive())
# True = on
# False = off

IDE (Spyder in my case) or python console

Disable interactive mode before the matplotlib commands:

plt.ioff()

Then you need an explicite plt.show() to display the plot.


Jupyter notebook

Heads-up, I had to install ipympl first to call %matplotlib widget (see the switch states below):

conda install -c conda-forge ipympl
pip install ipympl

See ipympl installing for more options.

Switch off:

%matplotlib widget
plt.ioff()

# matplotlib commands

Note: Then 'just' a plt.show() isn't enough to display the plot, see next step.

Switch on:

%matplotlib inline
# plt.ion()  # actually not required since 'inline' will switch in on automatically

# matplotlib commands 
#   in your case the myplot = plot_it_now()
#     a plt.show() like for the console isn't enough

Kudos to towardsdatascience How to produce Interactive Matplotlib Plots in Jupyter Environment and SO Matplotlib can't suppress figure window with its answers.
Since the latter one was about python 2.7 from the question I think an update is feasible.

MagnusO_O
  • 1,202
  • 4
  • 13
  • 19