使用函数和循环创建子图

Oli*_*ver 2 python plot matplotlib subplot

我有一个很好的函数,可以用两条线绘制一个图……它本身就可以很好地工作。然而,我想运行它 4 次以制作 2row x 2col 子图。我找不到一种好方法来多次运行该函数并将每个函数添加到子图中。

import matplotlib.pyplot as plt

patient = [['P1', [1,6,12,18,24], [15,17,16,19,15]],
           ['P2', [1,6,12,18,24], [12,13,17,18,18]],
           ['P3', [1,6,12,18,24], [19,19,12,11,9]],
           ['P4', [1,6,12,18,24], [8,7,3,12,15]]]

def plot_graph(patient):
    name = patient[0]
    X = patient[1]
    Y = patient[2]

    fig, ax = plt.subplots()

    #first line
    ax.plot([X[0],X[-1]],[Y[0],Y[-1]+20], marker='o', label='Line 1')

    #second line
    ax.plot(X,Y,marker='o',label='Line 2')

    #axis settings
    ax.set_ylim([0,80])
    ax.invert_yaxis()
    ax.set_title('My Graph')
    for x,y in zip(X,Y): ax.annotate(y,(x,y-4))
    ax.legend(loc=8)


plot_graph(patient[0])

plt.show()
Run Code Online (Sandbox Code Playgroud)

Tre*_*ney 5

  • 删除fig, ax = plt.subplots()并添加ax参数到函数
  • 迭代函数外部的子图。
    • .flattenaxes从 a转换(2, 2)(4, )数组,但这更容易迭代。
def plot_graph(data, ax):
    name = data[0]
    X = data[1]
    Y = data[2]

    #first line
    ax.plot([X[0],X[-1]],[Y[0],Y[-1]+20], marker='o', label='Line 1')

    #second line
    ax.plot(X,Y,marker='o',label='Line 2')

    #axis settings
    ax.set_ylim([0,80])
    ax.invert_yaxis()
    ax.set_title('My Graph')
    for x,y in zip(X,Y): ax.annotate(y,(x,y-4))
    ax.legend(loc=8)


fig, axes = plt.subplots(2, 2, figsize=(10, 8))
axes = axes.flatten()

for i, axe in enumerate(axes):
    plot_graph(data=patient[i], ax=axe)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述