删除图例重复项会在图例和线条之间留下不匹配的颜色(matplotlib,python)

Removing legend duplicates leaves unmatched colors between the legend and the lines (matplotlib, python)

我有多个 .dat 文件如下所示:first file and second file。 首先,我使用了这段代码:

z_bins = 541
h_bins = 65

for nr in [1,2]:
    array = []
    profile = "file_{}.dat".format(nr)
    d,h,en,de,dh = npy.loadtxt(profile,comments="#",unpack=True)

    s = 0
    e = z_bins

    selected = npy.linspace(0,z_bins-1,3)
 
    for i in selected:
        i = int(i)
        plt.plot(h[i:i+(h_bins-1)*z_bins:z_bins],en[i:i+(h_bins-1)*z_bins:z_bins],label='file{}' .format(nr))
       
    plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
    plt.ylim(-300,0)

除了图例重复之外,情节看起来应该是这样:

因此,我编辑了代码以删除重复的图例(代码中的最后 3 行):

z_bins = 541
h_bins = 65

for nr in [1,2]:
    array = []
    profile = "file_{}.dat".format(nr)
    d,h,en,de,dh = npy.loadtxt(profile,comments="#",unpack=True)

    s = 0
    e = z_bins

    selected = npy.linspace(0,z_bins-1,3)
 
    for i in selected:
        i = int(i)
        plt.plot(h[i:i+(h_bins-1)*z_bins:z_bins],en[i:i+(h_bins-1)*z_bins:z_bins],label='file{}' .format(nr))
       
    plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
    plt.ylim(-300,0)
    handles, labels = plt.gca().get_legend_handles_labels()
    by_label = dict(zip(labels, handles))
    plt.legend(by_label.values(), by_label.keys())

结果如下所示:

我很高兴图例重复项消失了,但是图例中的颜色与图表中线条的颜色不匹配。

我认为它发生是因为我从图例中删除了重复项,但它们 colors/lines 保留在情节本身中。 我想以图例中的颜色与线条颜色相匹配的方式修复它。 我试图以这种方式修复它:首先设置重复项具有相同的颜色(例如,所有 'file1' 都是蓝色,所有“file2' 都是红色),然后删除重复项本身。但是,我没有成功使用这种方法。有人可以帮我提出如何处理的建议吗?

我不确定你的方法是否有意义:剩下的四行是不可见的,因为它们大约为零(即它们都在图的顶部脊柱处一个接一个地绘制)。

但是,如果您知道总是只有一些具有重要值的行,您可以仅为这些行分配标签,并为不应出现在图例中的其余行分配下划线(以下划线开头的标签未包含在图例中):

    plt.plot(h[i:i+(h_bins-1)*z_bins:z_bins],
             en[i:i+(h_bins-1)*z_bins:z_bins],
             label='file{}'.format(nr) if min(en[i:i+(h_bins-1)*z_bins:z_bins]) < -10 else '_')