pythonplotjupyter-notebookhidesuppress

How to suppress output of a series of plots


I'm trying to suppress the output/plots run in the code below (because I plan on adjusting the plots later), but regardless of what I've tried, nothing seems to work.

I've tried all the following based on the referenced articles (littering my code, will need to clean up), but nothing seems to work.

Related SO:

    dictionary_of_figures = OrderedDict()
    dictionary_of_images = OrderedDict()
        
    from contextlib import contextmanager
    import sys, os
    import subprocess
    import inspect
    import contextlib
    import io
    import pandas as pd
    import matplotlib.pyplot as plt
    import seaborn as sns
    import numpy as np
    import matplotlib.ticker as ticker
    from collections import OrderedDict
      
    def draw_year_close_plot(df, group_by_column_name, year):
        reduced_range = df.loc[(df['Year'] == year)]
        year_string = str(year)
        
        # 0 - Setup
        matplotlib.rc_file_defaults();
        ax1 = sns.set_style("darkgrid"); #"style must be one of white, dark, whitegrid, darkgrid, ticks"
        fig, ax1 = plt.subplots(figsize=(5,2));
        # 1 - Create Closing Plot
        lineplot = sns.lineplot(data = reduced_range['Close'], sort = False, ax=ax1);
        pass;
        ax1.xaxis.set_major_formatter(ticker.EngFormatter())
        lineplot.set_title(company_name + str(" (")+ stock_ticker + str(") - ") + 'Historical Close & Volume - ' + year_string, fontdict= { 'fontsize': 8, 'fontweight':'bold'})
        # 2 - Create Secondary Plot - Volume
        ax2 = ax1.twinx();
        ax2.grid(False);
        sns.lineplot(data = reduced_range['Volume'], sort = False, ax=ax2, alpha=0.15);
        pass;
    
        return fig
    
    from IPython.core.interactiveshell import InteractiveShell
    InteractiveShell.ast_node_interactivity = "last_expr"
    
    #@contextmanager
    #def suppress_stdout():
    #    with open(os.devnull, "w") as devnull:
    #        old_stdout = sys.stdout
    #        sys.stdout = devnull
    #        try:  
    #            yield
    #        finally:
    #            sys.stdout = old_stdout
    
    
    #@contextlib.contextmanager
    #def nostdout():
    #    save_stdout = sys.stdout
    #    sys.stdout = io.BytesIO()
    #    yield
    #    sys.stdout = save_stdout
        
    with contextlib.redirect_stdout(io.StringIO()):
        for year in range(min_year,min_year+5):    
            dictionary_of_figures[year] = draw_year_close_plot(daily_df,'Year', year);
            dictionary_of_images[year] = fig2img(dictionary_of_figures[year]);
  


Any ideas?


Solution

  • It looks like you are asking to suppress plots while in the Jupyter environment. The %matplotlib inline causes the plots to be rendered on the output. If you remove that line, you will not get the plot rendered and you'll get back the plot object (I tested this on your code).

    You can't comment out %matplotlib inline once the kernel in Jupyter has run it - it persists within the kernel. You need to comment it out and restart the kernel, at which point I think you'll see the behavior you want.

    Once you've modified the plots as you with, you can turn %matplotlib inline back on and render your updated plots.

    If you need to turn %matplotlib inline on and off, you need to know a little about your Jupyter environment. Please see this answer

    UPDATE:

    I tried a few cases. It looks best if you explicitly set %matplotlib to an option other than inline. Here is minimal code to illustrate. I have kept all of your graphics-related code and made up data where your question does not provide values, and print the type for fig (which is your return value). I have also explicitly set %matplotlib notebook. Note that you should run %matplotlib --list to make sure that is one of your choices.

    import pandas as pd
    import matplotlib.pyplot as plt
    import seaborn as sns
    import matplotlib.ticker as ticker
    
    df = pd.DataFrame({'Close': [1,2,3], 'Volume': [4,5,6]})
    
    %matplotlib notebook 
    # matplotlib.rc_file_defaults() # We don't have your defaults file
    ax1 = sns.set_style("darkgrid"); #"style must be one of white, dark, whitegrid, darkgrid, ticks"
    fig, ax1 = plt.subplots(figsize=(5,2))
    lineplot = sns.lineplot(data=df['Close'], sort = False, ax=ax1)
    ax1.xaxis.set_major_formatter(ticker.EngFormatter())
    lineplot.set_title("This is the Title")
    ax2 = ax1.twinx()
    ax2.grid(False)
    sns.lineplot(data=df['Volume'], sort = False, ax=ax2, alpha=0.15)
    print(type(fig))