代码之家  ›  专栏  ›  技术社区  ›  Alexander

如何在matplotlib中设置列表中子站点的标题

  •  2
  • Alexander  · 技术社区  · 6 年前

    我试图从数据数组中设置子块的标题。

    我想要的是标题1,标题2。。。对于图中的(00、01、10和11)位置,依此类推。

    我就这样做了;

    import matplotlib.pyplot as plt    
    
    title = [1,2,3,4]
    
    fig, ax = plt.subplots(2, 2, figsize=(6, 8))  
    
        for i in range(len(ax)): 
            for j in range(len(ax[i])):
    
                for k in title:
                #    print (k)
                    ax[i,j].set_title('Title-' + str(k))
    

    但只拿到第四名。我怎样才能解决这个问题? 谢谢

    enter image description here

    2 回复  |  直到 6 年前
        1
  •  3
  •   Scott Boston    6 年前

    一种方法使用 flatten enumerate :

    import matplotlib.pyplot as plt    
    
    title = [1,2,3,4]
    
    fig, ax = plt.subplots(2, 2, figsize=(6, 8))  
    flat_ax = ax.flatten()
    
    for n, ax in enumerate(flat_ax):
        ax.set_title(f'Title-{title[n]}')
    

    输出:

    enter image description here

    另一种选择是 iter 具有 扁平化 :

    import matplotlib.pyplot as plt    
    
    title = [1,2,3,4]
    ititle = iter(title)
    
    fig, ax = plt.subplots(2, 2, figsize=(6, 8))  
    flat_ax = ax.flatten()
    
    for ax in flat_ax:
        ax.set_title(f'Title-{next(ititle)}')
    

    另外,请注意,我使用的f-string需要python 3.6+

        2
  •  1
  •   mathfux    6 年前

    发生这种情况是因为您正在为每个 i , j . 您需要重构您的代码,使其只对每个代码执行一个赋值 j型 :

    for i in range(len(ax)):
        for j in range(len(ax[i])):
            ax[i,j].set_title('Title-' + str(1+2*i+j))
    

    你也许还想编一本字典

    codes = {(0,0):1, (0,1):2, (1,0):3, (1,1):4}
    

    最后一行替换为

    ax[i,j].set_title('Title-' + str(codes[i,j]))