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

The Question :

308 people think this question is useful

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?

The Question Comments :
  • I am confused by your concern of creating an extra variable. You have to make those objects behind the scenes anyway.
  • @tcaswell Well let me try to assuage them. I do not want to create extra variables, because it adds complexity to the whole script. I’m trying to teach this to a bunch of students, and since they have’t used matplotlib before, I wanted to keep things as simple as possible. Also, if you take a look at Rob’s answer, its far simpler than the example shown on the website. I hope that helps.
  • I would argue that using the state machine interface makes it harder to understand in the long run because so much of it is being done ‘by magic’. Also, the convention is to use import matplotlib.pyplot as plt instead of PyPlot

The Answer 1

520 people think this answer is useful

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

Consider this sample (tested with Python 3.8.0):

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 20, 1000)
y1 = np.sin(x)
y2 = np.cos(x)

plt.plot(x, y1, "-b", label="sine")
plt.plot(x, y2, "-r", label="cosine")
plt.legend(loc="upper left")
plt.ylim(-1.5, 2.0)

enter image description here Slightly modified from this tutorial:

The Answer 2

39 people think this answer is useful

You can access the Axes instance (ax) with plt.gca(). In this case, you can use


You can do this either by using the label= keyword in each of your plt.plot() calls or by assigning your labels as a tuple or list within legend, as in this working example:

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-0.75,1,100)
y0 = np.exp(2 + 3*x - 7*x**3)
y1 = 7-4*np.sin(4*x)


However, if you need to access the Axes instance more that once, I do recommend saving it to the variable ax with

ax = plt.gca()

and then calling ax instead of plt.gca().

The Answer 3

14 people think this answer is useful

Here’s an example to help you out …

fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(111)
ax.set_title('ADR vs Rating (CS:GO)')
plt.plot(data[:,0], m*data[:,0] + b,color='red',label='Our Fitting 

enter image description here

The Answer 4

13 people think this answer is useful

A simple plot for sine and cosine curves with a legend.

Used matplotlib.pyplot

import math
import matplotlib.pyplot as plt
for i in range(-314,314):
ysin=[math.sin(i) for i in x]
ycos=[math.cos(i) for i in x]
plt.plot(x,ysin,label='sin(x)')  #specify label for the corresponding curve

Sin and Cosine plots (click to view image)

The Answer 5

7 people think this answer is useful

Add labels to each argument in your plot call corresponding to the series it is graphing, i.e. label = "series 1"

Then simply add Pyplot.legend() to the bottom of your script and the legend will display these labels.

The Answer 6

5 people think this answer is useful

You can add a custom legend documentation

first = [1, 2, 4, 5, 4]
second = [3, 4, 2, 2, 3]
plt.plot(first, 'g--', second, 'r--')
plt.legend(['First List', 'Second List'], loc='upper left')

enter image description here

The Answer 7

0 people think this answer is useful
    # Dependencies
    import numpy as np
    import matplotlib.pyplot as plt

    #Set Axes
    # Set x axis to numerical value for month
    x_axis_data = np.arange(1,13,1)

    # Average weather temp
    points = [39, 42, 51, 62, 72, 82, 86, 84, 77, 65, 55, 44]

    # Plot the line
    plt.plot(x_axis_data, points)

    # Convert to Celsius C = (F-32) * 0.56
    points_C = [round((x-32) * 0.56,2) for x in points]

    # Plot using Celsius
    plt.plot(x_axis_data, points_C)

    # Plot both on the same chart
    plt.plot(x_axis_data, points)
    plt.plot(x_axis_data, points_C)

    #Line colors
    plt.plot(x_axis_data, points, "-b", label="F")
    plt.plot(x_axis_data, points_C, "-r", label="C")

    #locate legend
    plt.legend(loc="upper left")

Add a Comment