6

Creating a certain plot is a lot of work, so I would like to automate this by create a function f() that returns a figure.

I would like to call this function so that I can put the result in a subplot. Is there anyway I can do this? Below is some psuedo code explaining what I mean

figure_of_interest = f()

fig,ax = plt.subplots(nrows = 4,cols = 1)

ax[1].replace_with(figure_of_interest)
Demetri Pananos
  • 6,770
  • 9
  • 42
  • 73

1 Answers1

1

This was asked before here and here.

Short answer: It is not possible.

But you can always modify the axes instance or use a function to create/modify the current axes:

import matplotlib.pyplot as plt
import numpy as np

def test():
    x = np.linspace(0, 2, 100)

    # With subplots
    fig1, (ax1, ax2) = plt.subplots(2)
    plot(x, x, ax1)
    plot(x, x*x, ax2)

    # Another Figure without using axes
    fig2 = plt.figure()
    plot(x, np.exp(x))

    plt.show()

def plot(x, y, ax=None):
    if ax is None:
        ax = plt.gca()
    line, = ax.plot(x, y)
    return line

test()
Community
  • 1
  • 1
MSeifert
  • 145,886
  • 38
  • 333
  • 352