简体   繁体   中英

multiple plots with function matplotlib

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.

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 在此处输入图片说明

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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM