1

I created a function that creates a plot, basically the function looks like this:

def draw_line(array):
    fig, ax = plt.subplots()
    ax.plot(array)

I wanted to know if there is a way to call this function when wanting to do multiple plots in a figure. In particular, I wanted to do something like:

fig, axes = plt.subplots(nrows=2, ncols=3)
for i in list:
axes[i] = draw_line(*list[i]) 

However, what I get is an empty grid with the actual plots below.

2 Answers 2

4

You don't want to call a new plt.subplots() each time you call draw_line(). Instead, you want to use an existing axis object. In this case you want to pass in the axis for each subplot with its corresponding data. Then plot the two together.

from matplotlib import pyplot as plt
import numpy as np

def draw_line(ax,array):
    # fig, ax = plt.subplots()
    ax.plot(array)

# example data and figure
example_list = [[1,2,3],[4,5,6],[3,2,5],[3,2,5],[3,2,5],[3,2,5]]
fig, axes = plt.subplots(nrows=2, ncols=3)

# loop over elements in subplot and data, plot each one
for ax,i in zip(axes.flatten(),example_list):
    draw_line(ax,i) 

Output looks like this enter image description here

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

2 Comments

Note, the pictures on the bottom row are all the same cause their data is the same. Just got lazy there. Also, the function draw_line() can be as crazy as you like, just pass in the individual axis object you want the data to be plotted on as in this example.
Thank you very much, just tried it and it works well!
2

Alternative to @user2241910,

from matplotlib import pyplot as plt

fig = plt.figure()
example_list = [[1,2,3],[4,5,6],[3,2,5],[5,2,3],[1,3,1],[5,3,5]]

for i,data in enumerate(example_list):
    ax = plt.subplot(2,3,i+1)
    ax.plot(data)

Produces:

enter image description here

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.