Bird
Raised Fist0
Matplotlibdata~10 mins

Plotting multiple lines in Matplotlib - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Plotting multiple lines
Start matplotlib setup
↓
Create figure and axes
↓
Prepare data for line 1
↓
Plot line 1
↓
Prepare data for line 2
↓
Plot line 2
↓
Add labels and legend
↓
Show plot
↓
End
This flow shows how matplotlib prepares and draws multiple lines step-by-step on the same plot.
Execution Sample
Matplotlib
import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y1 = [1, 4, 9, 16]
y2 = [2, 3, 5, 7]

plt.plot(x, y1, label='Squares')
plt.plot(x, y2, label='Primes')
plt.legend()
plt.show()
This code plots two lines on the same graph: squares and primes, then shows the plot with a legend.
Execution Table
StepActionData UsedPlot StateOutput
1Import matplotlib.pyplot as plt-No plot createdModule loaded
2Define x datax = [1, 2, 3, 4]No plot createdx data ready
3Define y1 datay1 = [1, 4, 9, 16]No plot createdy1 data ready
4Define y2 datay2 = [2, 3, 5, 7]No plot createdy2 data ready
5Plot line 1 with label 'Squares'x and y1One line plottedLine 1 drawn
6Plot line 2 with label 'Primes'x and y2Two lines plottedLine 2 drawn
7Add legendLabels from linesLegend addedLegend visible
8Show plotAll plotted lines and legendPlot window opensGraph displayed
9End-Plot shownExecution complete
💡 All lines plotted and displayed, program ends.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
xundefined[1, 2, 3, 4][1, 2, 3, 4][1, 2, 3, 4][1, 2, 3, 4]
y1undefinedundefined[1, 4, 9, 16][1, 4, 9, 16][1, 4, 9, 16]
y2undefinedundefinedundefined[2, 3, 5, 7][2, 3, 5, 7]
plot stateemptyemptyemptyemptytwo lines with legend
Key Moments - 3 Insights
Why do we call plt.plot() twice instead of once?
Each plt.plot() call adds one line to the plot. Calling it twice draws two separate lines, as shown in steps 5 and 6 of the execution_table.
What does plt.legend() do and why is it called after plotting lines?
plt.legend() collects labels from all plotted lines and shows a legend box. It must be called after plotting lines to know their labels, as in step 7.
Why doesn't the plot show until plt.show() is called?
plt.show() opens the plot window and renders the graph. Before this, lines are prepared but not displayed, as seen in step 8.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 6. How many lines are plotted after this step?
ATwo lines
BOne line
CNo lines
DThree lines
💡 Hint
Check the 'Plot State' column at step 6 in the execution_table.
According to variable_tracker, what is the value of y2 after step 4?
A[1, 4, 9, 16]
B[2, 3, 5, 7]
C[1, 2, 3, 4]
Dundefined
💡 Hint
Look at the 'y2' row and 'After Step 4' column in variable_tracker.
If we remove plt.legend(), what will happen to the plot output?
ALines will not be drawn
BPlot will not open
CPlot will show but without legend
DAn error will occur
💡 Hint
Refer to step 7 and 8 in execution_table about legend and plot display.
Concept Snapshot
Plotting multiple lines with matplotlib:
- Use plt.plot(x, y, label='name') for each line
- Call plt.legend() to show labels
- Call plt.show() to display the plot
- Each plt.plot() adds a new line
- Lines share the same axes by default
Full Transcript
This example shows how to plot multiple lines using matplotlib in Python. First, we import matplotlib.pyplot as plt. Then we prepare data lists for x and two y sets. We call plt.plot() twice, once for each line, passing x and y data with labels. After plotting lines, we call plt.legend() to add a legend box that shows line labels. Finally, plt.show() opens the plot window displaying both lines and the legend. Variables x, y1, and y2 hold the data arrays. The plot state changes from empty to having one line, then two lines, then the legend. This step-by-step process helps beginners see how multiple lines are added and displayed on the same graph.

Practice

(1/5)
1. What is the main way to plot multiple lines on the same graph using matplotlib?
easy
A. Use plt.hist() multiple times
B. Use plt.scatter() for each line
C. Call plt.plot() multiple times with different data sets before plt.show()
D. Call plt.bar() for each line

Solution

  1. Step 1: Understand plotting multiple lines

    In matplotlib, to plot multiple lines on the same graph, you call plt.plot() for each line's data before showing the plot.
  2. Step 2: Identify correct plotting function

    plt.scatter(), plt.bar(), and plt.hist() are for scatter plots, bar charts, and histograms, not line plots.
  3. Final Answer:

    Call plt.plot() multiple times with different data sets before plt.show() -> Option C
  4. Quick Check:

    Multiple plt.plot() calls = multiple lines [OK]
Hint: Use multiple plt.plot() calls to add lines [OK]
Common Mistakes:
  • Using plt.scatter() instead of plt.plot() for lines
  • Calling plt.show() after each line instead of once
  • Using bar or histogram functions for line plots
2. Which of the following code snippets correctly plots two lines on the same graph?
easy
A. plt.plot([1, 2, 3], [4, 5, 6]) plt.plot([1, 2, 3], [6, 5, 4]) plt.show()
B. plt.plot([1, 2, 3], [4, 5, 6]) plt.show() plt.plot([1, 2, 3], [6, 5, 4])
C. plt.show() plt.plot([1, 2, 3], [4, 5, 6]) plt.plot([1, 2, 3], [6, 5, 4])
D. plt.plot([1, 2, 3], [4, 5, 6]) plt.plot([1, 2, 3], [6, 5, 4])

Solution

  1. Step 1: Check order of plotting and showing

    To plot multiple lines, call plt.plot() for each line, then call plt.show() once at the end.
  2. Step 2: Identify correct snippet

    plt.plot([1, 2, 3], [4, 5, 6]) plt.plot([1, 2, 3], [6, 5, 4]) plt.show() calls plt.plot() twice then plt.show(), which is correct. plt.plot([1, 2, 3], [4, 5, 6]) plt.show() plt.plot([1, 2, 3], [6, 5, 4]) calls plt.show() too early, splitting the plots. plt.show() plt.plot([1, 2, 3], [4, 5, 6]) plt.plot([1, 2, 3], [6, 5, 4]) calls plt.show() before plotting, so nothing shows. plt.plot([1, 2, 3], [4, 5, 6]) plt.plot([1, 2, 3], [6, 5, 4]) misses plt.show() entirely.
  3. Final Answer:

    Two plt.plot() calls followed by plt.show() -> Option A
  4. Quick Check:

    Plot lines first, show once after [OK]
Hint: Call plt.show() only after all plt.plot() calls [OK]
Common Mistakes:
  • Calling plt.show() before all plots
  • Forgetting plt.show() to display plot
  • Plotting after plt.show() call
3. What will be the output of this code?
import matplotlib.pyplot as plt
x = [1, 2, 3]
y1 = [2, 4, 6]
y2 = [1, 3, 5]
plt.plot(x, y1, label='Line 1')
plt.plot(x, y2, label='Line 2')
plt.legend()
plt.show()
medium
A. A graph with two lines but no legend
B. A graph with two lines labeled 'Line 1' and 'Line 2'
C. A graph with one line labeled 'Line 2' only
D. No graph displayed due to error

Solution

  1. Step 1: Analyze plotting commands

    The code plots two lines with plt.plot() and assigns labels 'Line 1' and 'Line 2'.
  2. Step 2: Understand legend usage

    Calling plt.legend() displays the legend with the labels for both lines.
  3. Final Answer:

    A graph with two lines labeled 'Line 1' and 'Line 2' -> Option B
  4. Quick Check:

    Labels + plt.legend() = labeled lines [OK]
Hint: Use plt.legend() to show labels for all lines [OK]
Common Mistakes:
  • Forgetting plt.legend() so labels don't show
  • Assigning labels incorrectly
  • Plotting only one line
4. Identify the error in this code that tries to plot two lines:
import matplotlib.pyplot as plt
x = [1, 2, 3]
y1 = [2, 4, 6]
y2 = [1, 3, 5]
plt.plot(x, y1, label='Line 1')
plt.plot(x, y2, label='Line 2')
plt.legend
plt.show()
medium
A. Missing parentheses after plt.legend() call
B. x and y lists have different lengths
C. plt.show() is called before plotting
D. Labels are not assigned to lines

Solution

  1. Step 1: Check function calls

    The code calls plt.legend without parentheses, so the legend function is not executed.
  2. Step 2: Understand effect of missing parentheses

    Without calling plt.legend(), the legend does not appear, so labels won't show.
  3. Final Answer:

    Missing parentheses after plt.legend() call -> Option A
  4. Quick Check:

    Call plt.legend() with () to show legend [OK]
Hint: Always add () after plt.legend to display legend [OK]
Common Mistakes:
  • Forgetting () after plt.legend
  • Assuming legend shows without calling function
  • Mixing up order of plt.show()
5. You want to plot three lines with different colors and styles on the same graph and add a legend. Which code snippet correctly achieves this?
hard
A. plt.plot(x, y1, 'r-', label='Red solid') plt.plot(x, y2, 'g--') plt.plot(x, y3, 'b:') plt.legend() plt.show()
B. plt.plot(x, y1, color='red', linestyle='-', label='Red solid') plt.plot(x, y2, color='green', linestyle='--', label='Green dashed') plt.plot(x, y3, color='blue', linestyle=':', label='Blue dotted') plt.legend() plt.show()
C. plt.plot(x, y1, 'red', 'solid', label='Red solid') plt.plot(x, y2, 'green', 'dashed', label='Green dashed') plt.plot(x, y3, 'blue', 'dotted', label='Blue dotted') plt.legend() plt.show()
D. plt.plot(x, y1, 'r-', label='Red solid') plt.plot(x, y2, 'g--', label='Green dashed') plt.plot(x, y3, 'b:', label='Blue dotted') plt.legend() plt.show()

Solution

  1. Step 1: Understand color and style shorthand

    In matplotlib, shorthand like 'r-' means red solid line, 'g--' green dashed, 'b:' blue dotted.
  2. Step 2: Check label usage and legend

    plt.plot(x, y1, 'r-', label='Red solid') plt.plot(x, y2, 'g--', label='Green dashed') plt.plot(x, y3, 'b:', label='Blue dotted') plt.legend() plt.show() assigns labels to all lines and calls plt.legend() to show them. plt.plot(x, y1, color='red', linestyle='solid', label='Red solid') plt.plot(x, y2, color='green', linestyle='dashed', label='Green dashed') plt.plot(x, y3, color='blue', linestyle='dotted', label='Blue dotted') plt.legend() plt.show() uses invalid linestyle names ('solid', 'dashed', 'dotted' are not valid; correct are '-', '--', ':'). plt.plot(x, y1, 'red', 'solid', label='Red solid') plt.plot(x, y2, 'green', 'dashed', label='Green dashed') plt.plot(x, y3, 'blue', 'dotted', label='Blue dotted') plt.legend() plt.show() uses positional strings incorrectly. plt.plot(x, y1, 'r-', label='Red solid') plt.plot(x, y2, 'g--') plt.plot(x, y3, 'b:') plt.legend() plt.show() misses labels for second and third lines.
  3. Final Answer:

    Shorthand format strings like 'r-', 'g--', 'b:' for each plt.plot() -> Option D
  4. Quick Check:

    Use shorthand 'color-style' and label each line [OK]
Hint: Use shorthand like 'r-', 'g--', 'b:' with labels [OK]
Common Mistakes:
  • Using invalid linestyle names like 'solid'
  • Forgetting labels on all lines
  • Not calling plt.legend() to show labels
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard