Menu
CoddyTech

Several Lines and Legends

Part of the Data and Plots section of Coddy's Machine Learning journey. Lesson 22 of 60.

Comparing two things? Put them on one chart, like a pool and an ice rink over six months:

A chart titled Visitors per Month with two lines that cross near month 4: Pool climbs from 80 to 610 visitors, Ice rink falls from 540 to 60, and a legend names both

Each plt.plot adds a line, and label= gives it a name:

months = [1, 2, 3, 4, 5, 6]
pool = [80, 95, 150, 260, 420, 610]
rink = [540, 500, 380, 210, 120, 60]
plt.plot(months, pool, label="Pool")
plt.plot(months, rink, label="Ice rink")
plt.title("Visitors per Month")
plt.xlabel("Month")
plt.ylabel("Visitors")
plt.legend()
plt.show()

The lines cross near month 4, as the weather warms. plt.legend() draws the legend, each name beside its line's color. Without it, the names stay hidden.

challenge icon

Challenge

Medium

Two friends played six rounds of a board game. The program reads their names, one per line; scores1 and scores2 hold their points per round.

  1. Draw one line per player, rounds across and points up, the first player first.
  2. Name each line after its player and show a legend.

The starter sets the texts and shows the chart. Yours should look like this one, for Zoe and Sam:

A chart titled Game Scores with Round across and Points up: two zigzag lines over rounds 1 to 6, blue for Zoe and orange for Sam, and a legend naming Zoe then Sam

Your program prints nothing. Coddy describes your chart in the output.

Try it yourself

import matplotlib.pyplot as plt

player1 = input()
player2 = input()
rounds = [1, 2, 3, 4, 5, 6]
scores1 = [8, 12, 9, 15, 14, 18]
scores2 = [10, 9, 13, 12, 17, 16]

plt.title("Game Scores")
plt.xlabel("Round")
plt.ylabel("Points")

# Write your code below

# Don't change the line below
plt.show()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Data and Plots

Practice on your own: Online Python compiler