简体   繁体   English

Matplotlib子图在for循环内

[英]Matplotlib subplots inside a for loop

I have a function that takes in as input, 3 arrays and a constant value. 我有一个函数,将3个数组和一个常数作为输入。

Inside the function I am giving 10 different arrays with conditions and trying to plot them in 10 different subplots. 在函数内部,我给了10个带有条件的不同数组,并尝试将它们绘制在10个不同的子图中。

def ra_vs_dec(alpha,delta,zphot,mlim):
    zmin = [0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0,1.1,1.2]
    zmax = [0.4,0.5,0.6,0.7,0.8,0.9,1.0,1.1,1.2,1.3]
    plot_no = [1,2,3,4,5,6,7,8,9,10] # THESE ARE THE SUBPLOT NUMBERS

    for a,b,c in zip(zmin,zmax,plot_no):
        ra = alpha[(data_m200>mlim)*(data_z>a)*(data_z<b)] # RA FOR ZCOSMO
        dec = delta[(data_m200>mlim)*(data_z>a)*(data_z<b)] # DEC FOR ZCOSMO
        ra_zphot = alpha[(data_m200>mlim)*(zphot>a)*(zphot<b)] # RA FOR ZPHOT
        dec_zphot = delta[(data_m200>mlim)*(zphot>a)*(zphot<b)] # DEC FOR ZPHOT

        fig = plt.figure()
        ax = fig.add_subplot(2,5,c)
        ax.scatter(ra,dec,color='red',s=5.0,label=''+str(a)+'<zcosmo<'+str(b)+'')
        ax.scatter(ra_zphot,dec_zphot,color='blue',s=5.0,label=''+str(a)+'<zphot<'+str(b)+'')
        ax.legend(loc='best',scatterpoints=2)

    fig.show()

However, when I run the above code, I am getting only the final subplot, ie the 10th subplot. 但是,当我运行上面的代码时, 我只会得到最后的子图,即第十个子图。 What I am doing wrong here? 我在这里做错了什么?

I would like to see all the 10 subplots. 我想看到所有10个子图。

move the creation of the figure outside of the loop. 将图形的创建移出循环。 By having that inside the loop, you are creating 10 separate figures, and then adding only one subplot to each one. 通过在循环中包含该图形,可以创建10个单独的图形,然后在每个图形中仅添加一个子图形。 As you then use fig.show() , its only showing you the figure created in the final iteration. 然后,当您使用fig.show() ,它仅向您显示在最终迭代中创建的图形。

fig = plt.figure()

for a,b,c in zip(zmin,zmax,plot_no):
    ra = alpha[(data_m200>mlim)*(data_z>a)*(data_z<b)] # RA FOR ZCOSMO
    dec = delta[(data_m200>mlim)*(data_z>a)*(data_z<b)] # DEC FOR ZCOSMO
    ra_zphot = alpha[(data_m200>mlim)*(zphot>a)*(zphot<b)] # RA FOR ZPHOT
    dec_zphot = delta[(data_m200>mlim)*(zphot>a)*(zphot<b)] # DEC FOR ZPHOT

    ax = fig.add_subplot(2,5,c)
    ax.scatter(ra,dec,color='red',s=5.0,label=''+str(a)+'<zcosmo<'+str(b)+'')
    ax.scatter(ra_zphot,dec_zphot,color='blue',s=5.0,label=''+str(a)+'<zphot<'+str(b)+'')
    ax.legend(loc='best',scatterpoints=2)

fig.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM