Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (47.6k points)

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)")

As you can see, this is a very basic use of matplotlib's 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?

1 Answer

0 votes
by (106k points)

Add a label= to each of your plot() calls, and then call legend(loc='upper left').

Consider this sample:


Related questions

0 votes
1 answer
asked Oct 10, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Jul 2, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.5k answers


108k users

Browse Categories