【问题标题】:Adding subplots to figure using for loop使用 for 循环将子图添加到图形
【发布时间】:2020-07-21 22:35:00
【问题描述】:

我正在尝试将 8 个热图(子图)添加到图中,但我似乎无法管理它。请你帮助我好吗?

# in order to modify the size
fig = plt.figure(figsize=(12,8))
# adding multiple Axes objects  
fig, ax_lst = plt.subplots(2, 4)  # a figure with a 2x4 grid of Axes

letter = "ABCDEFGH"

for character in letter:
    x = np.random.randn(4096)
    y = np.random.randn(4096)
    heatmap, xedges, yedges = np.histogram2d(x, y, bins=(64,64))
    extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

    # Plot heatmap
    plt.clf()
    plt.title('Pythonspot.com heatmap example')
    plt.ylabel('y')
    plt.xlabel('x')
    plt.imshow(heatmap, extent=extent)
    plt.colorbar()
    plt.show()

谢谢!

【问题讨论】:

    标签: python numpy matplotlib statistics heatmap


    【解决方案1】:

    类似于this answer,您可以执行以下操作:

    letter = "ABCDEFGH"
    
    n_cols = 2
    fig, axes = plt.subplots(nrows=int(np.ceil(len(letter)/n_cols)), 
                             ncols=n_cols, 
                             figsize=(15,15))
    
    for _, ax in zip(letter, axes.flatten()):
        x = np.random.randn(4096)
        y = np.random.randn(4096)
        heatmap, xedges, yedges = np.histogram2d(x, y, bins=(64,64))
        extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
    
        # Plot heatmap
        ax.set_title('Pythonspot.com heatmap example')
        ax.set_ylabel('y')
        ax.set_xlabel('x')
        ax.imshow(heatmap, extent=extent)
    plt.tight_layout()  
    plt.show()
    

    【讨论】:

      【解决方案2】:

      首先,您通过调用创建两个单独的图形 plt.figure(),然后是 plt.subplots()(最后一个函数创建一个图形和一个轴数组)

      然后您需要遍历您的轴,并在每个轴上绘制,而不是在每个循环中清除图形(这就是您使用 plt.clf() 所做的)

      您可以使用plt.XXXX() 函数,但这些函数仅适用于“当前”轴,因此您必须在每次迭代时更改当前轴。否则,您最好使用Axes.set_XXXX() 函数,就像@yatu 的另一个答案一样。见here for more information。 fig, ax_lst = plt.subplots(2, 4, figsize=(12,8)) # 一个 2x4 轴网格的图形

      letters = "ABCDEFGH"
      for character,ax in zip(letters, ax_lst.flat):
          x = np.random.randn(4096)
          y = np.random.randn(4096)
          heatmap, xedges, yedges = np.histogram2d(x, y, bins=(64,64))
          extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
      
          # Plot heatmap
          plt.sca(ax) # make the ax object the "current axes"
          plt.title(character)
          plt.ylabel('y')
          plt.xlabel('x')
          plt.imshow(heatmap, extent=extent)
          plt.colorbar()
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-04
        相关资源
        最近更新 更多