Adding a legend to PyPlot in Matplotlib in the most simple manner possible
TL;DR -> How can one create a legend for a line graph in
PyPlotwithout creating any extra variables?
Please consider the graphing script below:
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()
As you can see, this is a very basic use of
PyPlot. This ideally generates a graph like the one below:
Nothing special, I know. However, it is unclear as to what data is being plotted where (I'm trying to plot the data of some sorting algorithms, length against time taken, and I'd like to make sure people know which line is which). Thus, I need a legend, however, taking a look at the following example below(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)
You will see that I need to create an extra variable
ax. How can I add a legend to my graph without having to create this extra variable and retaining the simplicity of my current script.
Consider this sample:
import numpy as np import pylab x = np.linspace(0, 20, 1000) y1 = np.sin(x) y2 = np.cos(x) pylab.plot(x, y1, '-b', label='sine') pylab.plot(x, y2, '-r', label='cosine') pylab.legend(loc='upper left') pylab.ylim(-1.5, 2.0) pylab.show()
Slightly modified from this tutorial: http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut1.html