函数matplotlib的多个绘图

2024-04-20 09:30:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个创建绘图的函数,基本上该函数如下所示:

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

我想知道,如果要在一个图形中绘制多个绘图,是否有方法调用此函数。特别是,我想做的是:

^{pr2}$

然而,我得到的是一个空网格,下面是实际的绘图。在


Tags: 方法函数图形绘图plotdeflinefig
2条回答

替代@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)

产生:

enter image description here

你不想叫一个新的plt.子批次()每次调用draw_line()时。而是使用现有的对象。在这种情况下,您需要为每个子批次传递轴及其相应的数据。然后把这两个画在一起。在

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) 

输出如下所示 enter image description here

相关问题 更多 >