0

I know this question comes up quite often, but despite reading tens of other SO questions (here, here, here, ... A search for [matplotlib] copy axes returns almost 200 results!), I couldn't find a solution to my case.

I have a function plotting something and returning the figure and the axes handles E.g.:

import numpy as np
import matplotlib.pyplot as plt

r = np.random.rand

def plot_something():
    x = np.linspace(0,10,100)
    y = r()*np.sin(r()*x+r())
    y2 = r(1000)*10

    fig, ax = plt.subplots()
    ax.plot(x,y)
    ax.hist(y2,density=True)

    return fig, ax

In the figure I have multiple artists of different types (e.g. rectangles and lines in the example above).

I want to generate a figure containing several axes (subplots) and, in a loop, call this function multiple times and populate the different axes of the figure.

The point is that I cannot change the first function.

In other words, I would like to do something like this:

fig, axs = plt.subplots(4,4)
for destination in axs.flatten():     
    fig2, ax = plot_something()
    # move/copy everything from ax to destination
    plt.close(fig2)
Luca
  • 1,610
  • 1
  • 19
  • 30
  • What do you mean by "# move/copy everything from ax to destination"? What is destination? You can pass the `ax` to the function using `fig2, ax = plot_something(ax=ax)` and then delete `fig, ax = plt.subplots()` from the function and write `def plot_something(ax=ax):` in the function definition – Sheldore Jun 08 '20 at 15:52
  • `destination` is the variable of the loop that is the destination axes I want to copy the content of `ax` to. I can’t modify the function and it does not accept the ax parameter – Luca Jun 08 '20 at 15:53
  • So you cannot pass `destination` to the function? – Sheldore Jun 08 '20 at 15:54
  • @Sheldore no, I can’t – Luca Jun 08 '20 at 15:55
  • The _standard_ way is to create a figure with a grid of subplots/axes and, in a loop, pass each one of the already existing axes to a plotting function. You are reversing this type of approach... What you want to do is probably possible but I guess that you should ask yourself "Need I to really have it my own way?" – gboffi Jun 08 '20 at 15:57
  • The plotting function comes from a package and perform a list of operation and I don't have access to it. If there is a better way I'll be happy to use it, but unfortunately I can't pass the plotting axes to the plotting function – Luca Jun 08 '20 at 15:59

0 Answers0