【问题标题】:Creating Subplots with a Function and Loop使用函数和循环创建子图
【发布时间】:2021-08-10 01:23:12
【问题描述】:

我有一个很好的函数,它可以用两条线绘制一个图……它本身就可以很好地工作。但是我想运行它 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()

【问题讨论】:

    标签: python matplotlib plot


    【解决方案1】:
    • 删除fig, ax = plt.subplots()并在函数中添加ax参数
    • 遍历函数外部的子图。
      • .flattenaxes(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)
    

    【讨论】:

    • 特伦顿!你又做了!你个巫师!!非常感谢您的帮助。
    • @Oliver 很高兴这对你有用。现在,如果我能用我的双手拍摄流星和灯光!
    猜你喜欢
    • 1970-01-01
    • 2014-05-18
    • 2022-01-08
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 2022-07-07
    • 1970-01-01
    相关资源
    最近更新 更多