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:
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
MediumTwo friends played six rounds of a board game. The program reads their names, one per line; scores1 and scores2 hold their points per round.
- Draw one line per player, rounds across and points up, the first player first.
- 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:
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()
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Data and Plots
2NumPy Arrays
Creating ArraysShape and SizeRanges of NumbersIndexing and SlicingRecap: Temperature Grid5Line and Scatter Plots
Labels and TitlesScatter PlotsSeveral Lines and LegendsColors and MarkersFigures and AxesRecap: Weekly StepsPractice on your own: Online Python compiler