Course Content
Visualization in Python with matplotlib
Visualization in Python with matplotlib
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:
# 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()
Thanks for your feedback!