Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Adding Legend to a Plot | Basics: Line Charts
Visualization in Python with matplotlib
course content

Contenido del Curso

Visualization in Python with matplotlib

Visualization in Python with matplotlib

1. Basics: Line Charts
2. Bar Charts
3. Scatter Plots

bookAdding Legend to a Plot

So far so good! You may remember that blue line refers to the first call of .plot() function, and the oragne line refers to the second call. But if someone other than you look on the chart, he will understand nothing. In this chapter, we will consider how to add a legend to a plot.

The easiest way to create a legend is to 'set' names while initializing plot. This can be done by setting the label parameter of .plot() function. After the labels are set, we can call plt.legend() before plt.show() to display the legend on the plot. For example, the code from the previous example can be modified in the following way:

123456789101112131415161718192021
# Import the libraries import matplotlib.pyplot as plt import pandas as pd # Load the data data = pd.read_csv('https://codefinity-content-media.s3.eu-west-1.amazonaws.com/ed80401e-2684-4bc4-a077-99d13a386ac7/co2.csv', index_col = 0) # Filter the data ita = data.loc['Italy'] swe = data.loc['Sweden'] # Create Figure and Axes objects fig, ax = plt.subplots() # Initialize lines ax.plot(ita.index.astype(int), ita.values, label = 'Italy') ax.plot(swe.index.astype(int), swe.values, label = 'Sweden') # Display the legend and plot plt.legend() plt.show()
copy

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 1. Capítulo 6
We're sorry to hear that something went wrong. What happened?
some-alt