Plotting on multiple figures with subplots in a single loop

后端 未结 2 1822
伪装坚强ぢ
伪装坚强ぢ 2021-01-19 17:21

I\'m plotting on two figures and each of these figures have multiple subplots. I need to do this inside a single loop. Here is what I do when I have only one figure:

<
2条回答
  •  日久生厌
    2021-01-19 17:45

    Here's a version that shows how to run scatter plots on two different figures. Basically you reference the axes that are created with plt.subplots.

    import matplotlib.pyplot as plt
    import numpy as np
    
    x1 = y1 = range(10)
    x2 = y2 = range(5)
    
    nRows = nCols = 6
    fig1, axesArray1 = plt.subplots(nrows=nRows,ncols=nCols,figsize=(20, 20))
    fig1.subplots_adjust(hspace=.5,wspace=0.4)
    fig1.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
    
    fig2, axesArray2 = plt.subplots(nrows=nRows,ncols=nCols,figsize=(20, 20))
    fig2.subplots_adjust(hspace=.5,wspace=0.4)
    fig2.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
    
    days = range(1, 32)
    dayRowCol = np.array([i + 1 for i in range(nRows * nCols)]).reshape(nRows, nCols)
    for day in days:
        rowIdx, colIdx = np.argwhere(dayRowCol == day)[0]
    
        axis1 = axesArray1[rowIdx, colIdx]
        axis1.set_title('day=' + str(day))
        axis1.scatter(x1, y1)
    
        axis2 = axesArray2[rowIdx, colIdx]
        axis2.set_title('day=' + str(day))
        axis2.scatter(x2, y2)
    
        # This didn't run in the original script, so I left it as is
        # plt.colorbar().set_label('Distance from ocean',rotation=270)
    
    fig1.savefig('plots/everyday_D1_color.png')
    fig2.savefig('plots/everyday_D2_color.png')
    plt.close('all')
    

    When I took the original code from the post plt.colorbar() raised an error, so I left it out in the answer. If you have an example of how colorbar was intended to work we could look at how to make that happen for two figures, but the rest of the code should work as intended!

    Note that if day every does not appear in dayRolCol numpy will raise an error, it's up to you to decide how you want to handle that case. Also, using numpy is definitely not the only way to do it, just a way I'm comfortable with - all you really need to do is find a way to link a certain day/plot with the (x, y) indices of the axis you want to plot on.

提交回复
热议问题