简体   繁体   English

具有功能matplotlib的多个图

[英]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(). 您不想每次调用draw_line()时都调用新的plt.subplots()。 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, @ 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: 产生:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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