Python 使用for循环将子批次添加到图形

Python 使用for循环将子批次添加到图形,python,numpy,matplotlib,statistics,heatmap,Python,Numpy,Matplotlib,Statistics,Heatmap,我试图在一个图中添加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:

我试图在一个图中添加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()
谢谢大家!

与类似,您可以执行以下操作:

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()

首先,您通过调用
plt.figure()

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

您可以使用
plt.XXXX()
函数,但这些函数只在“当前”轴上工作,因此您必须在每次迭代时更改当前轴。否则,您最好使用
轴。set_XXXX()
函数,就像@yatu的另一个答案一样。看见 图,ax_lst=plt.子图(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()

你应该能够让它按照复制的例子工作,唯一真正的变化是情节的类型。打我otherwise@yatu我尝试了,但是我得到了这个错误:RuntimeError:没有找到可用于创建颜色条的映射。首先定义一个可映射的图像(使用imshow)或轮廓集(使用contourf)。欢迎@laura别忘了你可以投票并接受答案。看,谢谢:)