0

I want to plot columns of a pandas dataframe by a calling a function. A data frame is passed to a function and manipulated. A plot and the manipulated data frame is returned:

from matplotlib import pyplot as plt
import pandas as pd

def custom_plot(df):
    tmp = df.plot(kind = 'bar')
    plt.legend(title = "Test")
    return  [tmp,df]

df = pd.DataFrame( {'x' : [1,2,3]})
p,d = custom_plot(df)

Executing this code displays this plot although I do not want it to be displayed:

enter image description here

I want to plot the returned object p in the Jupyter notebook by calling something like p.show(). There are 2 problems:

  1. The plot is always displayed when custom_plot() is called although I do not want it to be plotted.

  2. When I want to plot p by calling p.show() this does not work. I am told AttributeError: 'AxesSubplot' object has no attribute 'show'

How can this behavior be achieved?

HOSS_JFL
  • 765
  • 2
  • 9
  • 24
  • 1
    Why do you need the plot data, when you can call `df.plot()` wherever you need and get the plot? If you want to plot in a specific figure/subplot, that can be achieved using the `ax` argument in pandas' `plot` – gionni Sep 06 '21 at 07:28
  • I need this function because this plot is generated 20 times with different data frames. This minimal example does not represent the complexity of the problem at all. – HOSS_JFL Sep 06 '21 at 08:22
  • The link you posted does not help. None of the suggestions there change the output. – HOSS_JFL Sep 06 '21 at 08:23
  • @HOSS_JFL Oh sorry given a wrong link, I have deleted above comment as well. Please check https://stackoverflow.com/questions/30878666/matplotlib-python-inline-on-off – Rinshan Kolayil Sep 06 '21 at 08:33

2 Answers2

1

Perhaps this (partly) solves the issue:

from matplotlib import pyplot as plt
import pandas as pd

def custom_plot(df):
    tmp = df.plot(kind = 'bar')
    plt.legend(title = 'Test')
    fig = tmp.get_figure()
    plt.close()
    return fig, df

df = pd.DataFrame( {'x' : [1, 2, 3]})

p, d = custom_plot(df)

Closing the figure prevents it from showing. You can use p without the .show() to display the figure.

René
  • 4,594
  • 5
  • 23
  • 52
0

You can try using plt.ioff()

from matplotlib import pyplot as plt
import pandas as pd

def custom_plot(df):
    plt.ioff()
    df.plot(kind = 'bar')
    plt.legend(title = "Test")
    return  [plt,df]

df = pd.DataFrame( {'x' : [1,2,3]})
p,d = custom_plot(df)

p.show()

Output (There was no image after the first cell)

enter image description here

EDIT

from matplotlib import pyplot as plt
import pandas as pd
def custom_plot(df):
    f1 = plt.figure()
    ax1 = f1.add_subplot(111)
    df.plot(kind = 'bar',ax=ax1)
    ax1.legend(title='TEST')
    plt.close()
    return  [f1,df]

df = pd.DataFrame( {'x' : [1,2,3]})
p,d = custom_plot(df)

Now you can call p as well instead of p.show()

Rinshan Kolayil
  • 1,111
  • 1
  • 9
  • 14