Matplotlib 图例按递增顺序排列

esi*_*lik 3 matplotlib python-3.x

我有命名为 5.txt、10.txt、15.txt、20.txt 的文本文件,但是当我使用 glob 模块读取文件并在图例中使用 fname 变量时,我得到了混乱的图例数据。

for fname in glob("*.txt"):

    potential, current_density = np.genfromtxt(fname, unpack=True)
    current_density = current_density*1e6
    ax = plt.gca()
    ax.get_yaxis().get_major_formatter().set_useOffset(False)
    plt.plot(potential,current_density, label=fname[0:-4])

plt.legend(loc=4,prop={'size':12}, 
           ncol=1, shadow=True, fancybox=True,
           title = "Scan rate (mV/s)")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

如何以递增的顺序绘制并为数据提供相应的标签?

Imp*_*est 5

只是提供另一种方法,它不需要更改脚本绘图部分的任何内容:

handles, labels = plt.gca().get_legend_handles_labels()
handles, labels = zip(*[ (handles[i], labels[i]) for i in sorted(range(len(handles)), key=lambda k: list(map(int,labels))[k])] )
plt.legend(handles, labels, loc=4, ...)
Run Code Online (Sandbox Code Playgroud)