Add Legend
Now let's modify the plot from the previous task with the legend!
Aufgabe
Swipe to start coding
- Add
label
parameters to both plots. Use'United States'
aslabel
for theusa
data and'Canada'
for thecan
data. - Add a legend to the plot.
Lösung
# 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)
# Create Figure and Axes objects
fig, ax = plt.subplots()
# Save data for the US and Canada
usa = data.loc['United States']
can = data.loc['Canada']
# Initialize the plot
ax.plot(usa.index.astype(int), usa.values, label = 'United States')
ax.plot(can.index.astype(int), can.values, label = 'Canada')
# Display the legend and plot
plt.legend()
plt.show()
War alles klar?
Danke für Ihr Feedback!
Abschnitt 1. Kapitel 7
# 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)
# Create Figure and Axes objects
fig, ax = plt.subplots()
# Save data for the US and Canada
usa = data.loc['United States']
can = data.loc['Canada']
# Initialize the plot
ax.plot(usa.index.astype(int), usa.values, ___ = ___)
ax.plot(can.index.astype(int), can.values, label = '___')
# Display the legend and plot
plt.___()
plt.show()