Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Add Legend | Basics: Line Charts
Visualization in Python with matplotlib

book
Add Legend

Now let's modify the plot from the previous task with the legend!

Aufgabe

Swipe to start coding

  1. Add label parameters to both plots. Use 'United States' as label for the usa data and 'Canada' for the can data.
  2. 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?

Wie können wir es verbessern?

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()
toggle bottom row
some-alt