TL;DR -> How can one create a legend for a line graph in
Matplotlib
'sPyPlot
without creating any extra variables?
请考虑下面的绘图脚本:
if __name__ == '__main__':
PyPlot.plot(total_lengths, sort_times_bubble, 'b-',
total_lengths, sort_times_ins, 'r-',
total_lengths, sort_times_merge_r, 'g+',
total_lengths, sort_times_merge_i, 'p-', )
PyPlot.title("Combined Statistics")
PyPlot.xlabel("Length of list (number)")
PyPlot.ylabel("Time taken (seconds)")
PyPlot.show()
如你所见,这是matplotlib
's PyPlot
的一个非常基本的用法.理想情况下,这会生成如下所示的图形:
没什么特别的,我知道.然而,目前还不清楚哪些数据被绘制在哪里(我试图绘制一些排序算法的数据,长度与所用时间的关系,我想确保人们知道哪一行是哪一行).因此,我需要一个传说,但是,看看下面的例子(from the official site):
ax = subplot(1,1,1)
p1, = ax.plot([1,2,3], label="line 1")
p2, = ax.plot([3,2,1], label="line 2")
p3, = ax.plot([2,3,1], label="line 3")
handles, labels = ax.get_legend_handles_labels()
# reverse the order
ax.legend(handles[::-1], labels[::-1])
# or sort them by labels
import operator
hl = sorted(zip(handles, labels),
key=operator.itemgetter(1))
handles2, labels2 = zip(*hl)
ax.legend(handles2, labels2)
你会发现我需要创建一个额外的变量ax
.我怎样才能在我的graph without中添加一个图例,既要创建这个额外的变量,又要保持当前脚本的简单性?