Home > Back-end >  How can I plot a subplot and a dynamic figure with matplotlib side by side?
How can I plot a subplot and a dynamic figure with matplotlib side by side?

Time:12-23

I have a bitmapped image that I show/plot then I have an array of smaller images that I want to show next to the main image plot. I can plot both of them seperately but Im having a hard time combining them. The number of smaller images can change but I dont think thats an issue.

    # bitmapped image
    fig1, ax1 = plt.subplots()
    ax1.imshow(im, cmap='gray', vmin=0, vmax=1)
    plt.show()
    
    # smaller images I want to plot
    fig2 = plt.figure(figsize=(8, 8))
    columns = int(sqrt(len(indices)))  # say this is 5
    rows = int(ceil(sqrt(len(indices)))) # say this is also 5
    # ax enables access to manipulate each of subplots
    ax2 = []
    for i in range(columns*rows):
        # create subplot and append to ax
        if i < len(indices):
            ax2.append(fig2.add_subplot(rows, columns, i 1) )
            ax2[-1].set_title(f"Q: {tiles_dictionary[i]}")  # set title
            plt.imshow(val[i].reshape(S,S), cmap='gray', vmin=0, vmax=1)
            plt.axis('off')
    plt.show()

I tried a few different ways of combining the plots but the closest I got was having the plots overlay each other. This is roughly like what I would like it to look like.

enter image description here

CodePudding user response:

I was able to get it to work using gridspec, as shown below.

    fig = pyplot.figure(figsize=(8, 8))

    columns = int(sqrt(len(indices)))
    rows = int(ceil(sqrt(len(indices))))
    gs0 = gridspec.GridSpec(1, 2)
    gs00 = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=gs0[0])
    gs01 = gridspec.GridSpecFromSubplotSpec(rows, columns, subplot_spec=gs0[1])

    ax00 = fig.add_subplot(gs00[0])
    ax00.imshow(im, cmap='gray', vmin=0, vmax=1)

    for i in range(rows):
        for j in range(columns):
            unique_tile = columns*i j
            if unique_tile < len(indices):
                ax01 = fig.add_subplot(gs01[i, j])
                ax01.imshow(val[i j].reshape(S,S), cmap='gray', vmin=0, vmax=1)
                ax01.set_title(f"Q: {tiles_dictionary[i]}") 
                ax01.axis('off')
    pyplot.show()

enter image description here

  • Related