Adding a legend to PyPlot in Matplotlib in the simplest manner possible

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

TL;DR -> How can one create a legend for a line graph in Matplotlib"s PyPlot without 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)")

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

👻 Read also: what is the best laptop for engineering students?


Learn programming in R: courses


Best Python online courses for 2022


Best laptop for Fortnite


Best laptop for Excel


Best laptop for Solidworks


Best laptop for Roblox


Best computer for crypto mining


Best laptop for Sims 4


Latest questions


psycopg2: insert multiple rows with one query

12 answers


How to convert Nonetype to int or string?

12 answers


How to specify multiple return types using type-hints

12 answers


Javascript Error: IPython is not defined in JupyterLab

12 answers



Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method