Home > Mobile >  function to return pyplot object but not plot it unless explicitly specified
function to return pyplot object but not plot it unless explicitly specified

Time:09-27

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()

CodePudding user response:

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.

  • Related