0

I created a function that takes some inputs and creates a graph out of it. And now I want to return that subplot graph from the function which can be plotted later or used on the web page.

My function looks something like this (just a dummy representation)

def plot_g(x, y):
    # subplots
    fig, ax = plt.subplots(1, 2, figsize=(18, 14))
    
    # bar
    sns.barplot(x, y, ax= ax[0][0]
    
    # pie
    ax[0][1].pie(x,y)

I don't know what and how to do it, I also tried to follow this answer, but I am not able to understand and apply that here.

Darkstar Dream
  • 1,649
  • 1
  • 12
  • 23
  • 1
    More flexible is to pass the ax to the function rather than create one – Jody Klymak Jan 09 '22 at 12:25
  • Please explain exactly what do you want to do with the figure later. – OnY Jan 09 '22 at 12:25
  • 1
    You write *"I want to return that subplot graph from the function which can be plotted later"*. Well, matplotlib doesn't work that way. You need to call the function at the moment you want to plot, not earlier. As mentioned by Jody Klymak, the recommended way to do so, passes the `ax` as a parameter to the function. – JohanC Jan 09 '22 at 12:35

1 Answers1

0

You can simply return ax and fig:

def plot_g(x, y):
    # subplots
    fig, ax = plt.subplots(1, 2, figsize=(18, 14))
    
    # bar
    sns.barplot(x, y, ax= ax[0][0]
    
    # pie
    ax[0][1].pie(x,y)
     
    return fig, ax

or return just ax with return ax.

Then you can use ax as needed.

axs=plot_g(x, y)
axs[0][0].set_xlabel("Changed x Label")
OnY
  • 897
  • 6
  • 12
  • now after getting `axs ` how can I plot all graphs that are subplots. I am kind of trying to get it stored in a variable, which I call whenever I want to plot my all graph. – Darkstar Dream Jan 09 '22 at 12:46