for循环中的图例工作不正常,只显示最后一个cu

2024-05-12 19:27:51 发布

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

我尝试将7曲线的标签放在图例中,但是当显示绘图时,第7条曲线的标签在绘图上,其他6条曲线没有任何标签

我尝试在不同的缩进中使用plt.legend(),但是在第3个for循环中我们有7个以上的标签,因为z的for循环与其他for循环中的1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3...一样,图例无法出现

我们应该有1 2 3 4 5 6 7。 需要帮忙吗

for x in range(len(ng)):
    fig, (ax1) = plt.subplots(1,figsize=(9,6))
    plt.subplots_adjust(wspace=0.5,hspace=0.1)
    for xx in range(1,819):
            Ju_list=[]
            ET_list=[]
            ET1_list=[]
            Unu_list=[]
            z_list=[]
            uf_list=[]
            for z in np.arange(0,11):
                    Ju = dfimppara.iloc[xx, 1]
                    Jl = dfimppara.iloc[xx, 2]
                    lim = Ju - Jl
                    if lim > 1:
                        pass
                    else:
                        if Ju<8:

                            Ju_list.append(dfimppara.iloc[xx, 1])
                            T = ET(xx, z, ng[x], 1e-24, Tg[x], 1)
                            BC = Bcmb(xx,z)
                            Btex = B(xx,T)
                            ET_list.append(1-BC/Btex)
                            z_list.append(z)              
                            l1,=ax1.plot(z_list, ET_list)

                            ax1.title.set_text(f'UF=1e-24,Tg={Tg[x]},ng={ng[x]}')
                            ax1.set_ylabel('1-BB(CMB)/BB(Tex)')
                            ax1.set_xlabel('z')
                            plt.legend([l1],[f'{dfimppara.iloc[xx, 1]}'])


                        else:
                            pass

    plt.show()

Tags: inforplttg标签ng曲线list
1条回答
网友
1楼 · 发布于 2024-05-12 19:27:51

首先,您应该考虑在for循环之外创建空列表,否则每次迭代都会重新创建它们(除非这是您想要的)

关于图例问题,我建议您将'label'参数添加到每个plot()命令中,然后legend()将自己创建一个

示例:

# [...]
plt.figure()
plt.plot(x_data, y_data, label='Some label')  
plt.plot(more_x_data, more_y_data, label='Some other label')
plt.legend()  

将生成包含每个标签的图例。 在循环的每次迭代过程中,请注意附加到列表中的数据

相关问题 更多 >