1

python 3.6 om mac matplotlib 2.1.0 using matplotlib.pyplot (as plt)

Let's say i have a few plt.figures() that i appended into a list called figures as objects. When in command line i do: figures[0]it produces the plot for the index 0 of the list figures. However, how can i arrange to have all the plots in figures to be in a subplot.

# Pseudo code: 
plt.figure() 
for i, fig in enumerate(figures):   # figures contains the plots
    plt.subplot(2, 2, i+1)
    fig   # location i+1 of the subplot is filled with the fig plot element  

So as a result, i would a 2 by 2 grid that contains each plot found in figures.

hoping this makes sense.

1 Answer 1

4

A figure is a figure. You cannot have a figure inside a figure. The usual approach is to create a figure, create one or several subplots, plot something in the subplots.

In case it may happen that you want to plot something in different axes or figures, it might make sense to wrap the plotting in a function which takes the axes as argument.

You could then use this function to plot to an axes of a new figure or to plot to an axes of a figure with many subplots.

import numpy as np
import matplotlib.pyplot as plt

def myplot(ax, data_x, data_y, color="C0"):
    ax.plot(data_x, data_y, color=color)
    ax.legend()

x = np.linspace(0,10)
y = np.cumsum(np.random.randn(len(x),4), axis=0)

#create 4 figures
for i in range(4):
    fig, ax = plt.subplots()
    myplot(ax, x, y[:,i], color="C{}".format(i))

# create another figure with each plot as subplot
fig, ax = plt.subplots(2,2)
for i in range(4):
    myplot(ax.flatten()[i], x, y[:,i], color="C{}".format(i))

plt.show()

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.