Adding 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:
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 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()
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()
Alt var klart?
Takk for tilbakemeldingene dine!
Seksjon 1. Kapittel 6
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår