gpt4 book ai didi

python-3.x - Matplotlib 图例按升序排列

转载 作者:行者123 更新时间:2023-12-02 09:21:12 24 4
gpt4 key购买 nike

我有名为 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)")

enter image description here

如何按升序绘制数据并为其赋予相应的标签?

最佳答案

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

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, ...)

关于python-3.x - Matplotlib 图例按升序排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42519062/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com