使用除法对多个子图进行索引

2024-05-16 09:19:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我从一个包含反应结果的数据框中创建了多个子图(每个数据框70个),我想在进行更彻底的分析之前,将反应12乘12绘制出来,以便快速查看。由于70/12留下了一个余数,一个简单的实现将超出范围。我可以用一个“if,else”语句来解决这个问题,但它既不优雅也不高效。我想知道有没有更好的选择。 warDf的尺寸是70,meanDf的尺寸是130x70。时间、pcmean和ncmean的大小为130。我正在使用pandas(pd)、numpy(np)和matplotlib.pyplot文件(plt)

it=int(np.ceil(np.size(warDf)/12))# defining what to loop over
kk=0

for kk in np.arange(0,it): 
    #declaring the subplots 
    fig,axes=plt.subplots(nrows=3,ncols=4,sharex='col',sharey='row')
    #transforming axes in a usable list
    axe_list=[item for sublist in axes for item in sublist]

    # checking that I don't run out of bond
    if (12*kk+12<np.size(warDf)):
        k=0 
        # plotting each graph in its corresponding subplot
        for k in np.arange(0,12):                

            ax=axe_list.pop(0)
            ax.plot(time,meanDf.iloc[:,12*kk+k],label=(meanDf.columns[12*kk+k]),color='blue')
            ax.plot(time,pcmean,color='green')
            ax.plot(time,ncmean,color='red')
            ax.set_ylabel('fluorescence')
            ax.set_xlabel('time/ (s)')
            ax.legend()
    else: # better option??
        k=0
        s2=np.size(warDf)-12*kk
        for k in np.arange(0,s2):
            ax=axe_list.pop(0)
            ax.plot(time,meanDf.iloc[:,12*kk+k],label=(meanDf.columns[12*kk+k]),color='blue')
            ax.plot(time,pcmean,color='green')
            ax.plot(time,ncmean,color='red')
            ax.set_ylabel('fluorescence')
            ax.set_xlabel('time/ (s)')
            ax.legend()

plt.show()

Tags: infortimeplotnppltaxlist
1条回答
网友
1楼 · 发布于 2024-05-16 09:19:39

您可以使用min()函数。将整个if/else替换为:

k=0 # note: you don't have to pre-define k here

s2 = min(np.size(warDf) - 12 * kk, 12) # new part

for k in np.arange(0,s2): # the rest is the same as in the body of the else
    ax=axe_list.pop(0)
    ax.plot(time,meanDf.iloc[:,12*kk+k],label=(meanDf.columns[12*kk+k]),color='blue')
    ax.plot(time,pcmean,color='green')
    ax.plot(time,ncmean,color='red')
    ax.set_ylabel('fluorescence')
    ax.set_xlabel('time/ (s)')
    ax.legend()

说明

你现在有

if (12 * kk + 12 < np.size(warDf)):
    s2 = 12 # define s2 as a variable here as well
    for k in np.arange(0, s2):
        # ...
else:
    s2 = np.size(warDf) - 12 * kk 
    for k in np.arrange(0, s2):
        # ...

重新排列第一个if,我们可以得到:

if (12 < np.size(warDf) - 12 * kk):
    s2 = 12
    # ...
else:
    s2 = np.size(warDf) - 12 * kk
    # ...

现在您可以看到if的右侧和s2的赋值是相同的。如果12小于12,则使用12。否则,使用np.size(warDf) - 12 * kk。这是min()的定义。你知道吗

相关问题 更多 >