代码之家  ›  专栏  ›  技术社区  ›  Fbio Lds

在python中的for循环中创建图时,如何绘制子图?

  •  0
  • Fbio Lds  · 技术社区  · 8 年前

    我对编程不熟悉,目前一直坚持这一点:我使用for循环创建4个不同的绘图,我想将每个绘图分配给不同的子绘图。基本上,我想在2x2网格中绘制4个图,以便比较数据。有人知道我如何做到这一点吗?我的方法是创建子图列表,然后使用嵌套图将每个图分配给子图:

    import matplotlib.pyplot as plt
    import numpy as np
    
    def load_file(filename):
        return np.loadtxt(filename, delimiter=',', usecols=(0, 1), unpack=True, skiprows=1)
    
    
    fig = plt.figure()
    
    ax1 = fig.add_subplot(221)
    ax2 = fig.add_subplot(222)
    ax3 = fig.add_subplot(223)
    ax4 = fig.add_subplot(224)
    
    ax_list=[ax1, ax2, ax3, ax4]
    
    for i,filename in enumerate(file_list):
        for p in ax_list:
            x,y = load_file(filename)
            plt.plot(x,y,
            label=l, #I assign labels from a list beforehand, as well as colors
            color=c,
            linewidth=0.5,
            ls='-',
                   )
            p.plot()
    

    问题是,所有的图都只分配给一个子图,我不知道如何纠正这一点。如果有任何帮助,我将不胜感激!

    2 回复  |  直到 8 年前
        1
  •  1
  •   ImportanceOfBeingErnest    8 年前

    我想你想要的是在所有4个图上显示不同的数据,因此使用一个循环。确保使用轴打印方法,而不是 plt.plot 因为后者总是在最后一个子图中绘制。

    import matplotlib.pyplot as plt
    import numpy as np
    
    def load_file(filename):
        return np.loadtxt(filename, delimiter=',', usecols=(0, 1), unpack=True, skiprows=1)
    
    fig, ax_list = plt.subplots(2,2)
    
    for i,(filename,ax) in enumerate(zip(file_list, ax_list.flatten())):
        x,y = load_file(filename)
        ax.plot(x,y, linewidth=0.5,ls='-' )
    plt.show()
    
        2
  •  0
  •   Ken Syme    8 年前

    您不需要在文件名和绘图上循环,只需要选择列表中的下一个绘图。

    for i, filename in enumerate(file_list):
        p = ax_list[i]:
        x,y = load_file(filename)
        p.plot(x, y,
            label=l, #I assign labels from a list beforehand, as well as colors
            color=c,
            linewidth=0.5,
            ls='-')
    
    plt.plot()
    

    您也可以替换

    fig = plt.figure()
    
    ax1 = fig.add_subplot(221)
    ax2 = fig.add_subplot(222)
    ax3 = fig.add_subplot(223)
    ax4 = fig.add_subplot(224)
    
    ax_list=[ax1, ax2, ax3, ax4]
    

    只有

    fig, ax_list = plt.subplots(2, 2)
    ax_list = ax_list.flatten()
    

    获得一个简单的2x2网格。