How do I add a Matplotlib legend without extra variables?
I want to include a Matplotlib legend in my PyPlot line graph without introducing additional variables.
Here’s my current script:
if __name__ == '__main__':
PyPlot.plot(length, bubble, 'b-',
length, ins, 'r-',
length, merge_r, 'g+',
length, merge_i, 'p-', )
PyPlot.title("Combined Statistics")
PyPlot.xlabel("Length of list (number)")
PyPlot.ylabel("Time taken (seconds)")
PyPlot.show()
The graph is generated correctly, but it’s unclear which line represents which dataset. Official examples suggest using an extra ax
variable, but I want to keep my script simple.
Matplotlib allows adding labels directly inside plot(), and you can enable the legend by calling legend() before show():
import matplotlib.pyplot as PyPlot
if __name__ == '__main__':
PyPlot.plot(length, bubble, 'b-', label="Bubble Sort")
PyPlot.plot(length, ins, 'r-', label="Insertion Sort")
PyPlot.plot(length, merge_r, 'g+', label="Recursive Merge Sort")
PyPlot.plot(length, merge_i, 'p-', label="Iterative Merge Sort")
PyPlot.title("Combined Statistics")
PyPlot.xlabel("Length of list (number)")
PyPlot.ylabel("Time taken (seconds)")
PyPlot.legend() # Enable legend without extra variables
PyPlot.show()
Each plot() line includes a label=“…” argument.
PyPlot.legend() automatically detects labels and displays them.
If modifying each plot() call isn’t ideal, another approach is passing all labels together:
import matplotlib.pyplot as PyPlot
if name == ‘main’:
PyPlot.plot(length, bubble, ‘b-’)
PyPlot.plot(length, ins, ‘r-’)
PyPlot.plot(length, merge_r, ‘g+’)
PyPlot.plot(length, merge_i, ‘p-’)
PyPlot.title("Combined Statistics")
PyPlot.xlabel("Length of list (number)")
PyPlot.ylabel("Time taken (seconds)")
PyPlot.legend(["Bubble Sort", "Insertion Sort", "Recursive Merge Sort", "Iterative Merge Sort"]) # Labels manually defined
PyPlot.show()
Why this works?
legend() takes a list of labels in the same order as plot().
No need to modify plot() calls.
If you dynamically generate plots and don’t want to manually track labels, let Matplotlib extract them automatically:
import matplotlib.pyplot as PyPlot
if __name__ == '__main__':
PyPlot.plot(length, bubble, 'b-', label="Bubble Sort")
PyPlot.plot(length, ins, 'r-', label="Insertion Sort")
PyPlot.plot(length, merge_r, 'g+', label="Recursive Merge Sort")
PyPlot.plot(length, merge_i, 'p-', label="Iterative Merge Sort")
PyPlot.title("Combined Statistics")
PyPlot.xlabel("Length of list (number)")
PyPlot.ylabel("Time taken (seconds)")
handles, labels = PyPlot.gca().get_legend_handles_labels()
PyPlot.legend(handles, labels) # Automatically extracts labeled plots
PyPlot.show()
Why this works?
Extracts all labelled plots dynamically using get_legend_handles_labels().
Useful when plots are generated in loops or dynamically.