一个简单的按照另一个列表排序标签的方法如下:
在将所有的图和标签添加到轴上后,在显示标签之前进行以下步骤。
handles,labels = ax.get_legend_handles_labels()
sorted_legends= [x for _,x in sorted(zip(k,labels),reverse=True)]
sorted_handles=[x for _,x in sorted(zip(k,handles),reverse=True)]
ax.legend(sorted_handles,sorted_legends,bbox_to_anchor=(1,0.5), loc='center left')
例子:
from matplotlib import pyplot as plt
import numpy as np
rollno=np.arange(1,11)
marks_math=np.random.randint(30,100,10)
marks_science=np.random.randint(30,100,10)
marks_english=np.random.randint(30,100,10)
print("Roll No. of the students: ",rollno)
print("Marks in Math: ",marks_math)
print("Marks in Science: ",marks_science)
print("Marks in English: ",marks_english)
average=[np.average(marks_math),np.average(marks_science),np.average(marks_english)]
fig1=plt.figure()
ax=fig1.add_subplot(1,1,1)
ax.set_xlabel("Roll No.")
ax.set_ylabel("Marks")
ax.plot(rollno,marks_math,c="red",label="marks in math, Mean="+str(average[0]))
ax.plot(rollno,marks_science,c="green",label="marks in science, Mean="+str(average[1]))
ax.plot(rollno,marks_english,c="blue",label="marks in english, Mean="+str(average[2]))
handles,labels=ax.get_legend_handles_labels()
sorted_legends= [x for _,x in sorted(zip(average,labels),reverse=True)]
sorted_handles=[x for _,x in sorted(zip(average,handles),reverse=True)]
ax.legend(sorted_handles,sorted_legends,bbox_to_anchor=(1,0.5), loc='center left')
plt.show()
plt.close()
对于一个具有以下数值的运行:
Roll No. of the students: [ 1 2 3 4 5 6 7 8 9 10]
Marks in Math: [66 46 44 70 37 72 93 32 81 84]
Marks in Science: [71 99 99 40 59 80 72 98 91 81]
Marks in English: [46 64 74 33 86 49 84 92 67 35]
The average in each subject [62.5, 79.0, 63.0]
这些标签本来会按照绘图中的顺序出现,即红色、绿色和蓝色,但是我们希望根据平均值对它们进行排序,这样就会给我们一个绿色、蓝色和红色的顺序。
查看这张图片