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:
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()
Takk for tilbakemeldingene dine!
Spør AI
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
Awesome!
Completion rate improved to 2.94
Adding Legend to a Plot
Sveip for å vise menyen
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()
Takk for tilbakemeldingene dine!