Bird
Raised Fist0
Matplotlibdata~10 mins

Before-after comparison plots in Matplotlib - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Before-after comparison plots
Load Data
Identify Before and After
Choose Plot Type
Create Plot
Display Comparison
Interpret Results
The flow shows loading data, separating before and after values, choosing a plot style, creating the plot, displaying it, and interpreting the visual comparison.
Execution Sample
Matplotlib
import matplotlib.pyplot as plt
before = [5, 7, 8, 6]
after = [6, 9, 7, 8]
plt.plot(before, label='Before')
plt.plot(after, label='After')
plt.legend()
plt.show()
This code plots two lines showing values before and after an event for easy visual comparison.
Execution Table
StepActionVariable/Plot StateOutput/Result
1Import matplotlib.pyplot as pltplt module readyNo output
2Define before = [5,7,8,6]before = [5,7,8,6]No output
3Define after = [6,9,7,8]after = [6,9,7,8]No output
4Plot before lineLine for before plottedLine graph with before values
5Plot after lineLine for after plottedLine graph with before and after lines
6Add legendLegend with 'Before' and 'After'Legend displayed on plot
7Show plotPlot window opensVisual comparison of before and after lines
8EndPlot displayedExecution stops
💡 Plot displayed and program ends
Variable Tracker
VariableStartAfter Step 2After Step 3Final
beforeundefined[5,7,8,6][5,7,8,6][5,7,8,6]
afterundefinedundefined[6,9,7,8][6,9,7,8]
pltundefinedmodule importedmodule importedmodule imported
Key Moments - 3 Insights
Why do we plot both 'before' and 'after' on the same graph?
Plotting both on the same graph lets us visually compare changes directly, as shown in execution_table steps 4 and 5.
What does plt.legend() do in the plot?
plt.legend() adds labels to the lines so we know which is 'Before' and which is 'After', as seen in step 6.
Why do we call plt.show() at the end?
plt.show() opens the plot window so we can see the graph; without it, the plot won't display, as in step 7.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 5, what is plotted?
AOnly the 'before' line
BBoth 'before' and 'after' lines
COnly the 'after' line
DNo lines plotted yet
💡 Hint
Check the 'Variable/Plot State' column at step 5 in execution_table
At which step does the legend get added to the plot?
AStep 6
BStep 5
CStep 4
DStep 7
💡 Hint
Look at the 'Action' column in execution_table for when plt.legend() is called
If we swapped the order of plotting 'before' and 'after', what would change in the plot?
AThe plot would show only one line
BNothing would change visually
CThe lines would swap colors and legend order
DThe plot would not display
💡 Hint
Consider how matplotlib assigns colors and legend labels in the order of plotting
Concept Snapshot
Before-after comparison plots:
- Plot 'before' and 'after' data on the same graph
- Use plt.plot() for each dataset
- Add plt.legend() to label lines
- Call plt.show() to display
- Helps visually compare changes over time
Full Transcript
This visual execution shows how to create before-after comparison plots using matplotlib in Python. First, we import the plotting library. Then, we define two lists: 'before' and 'after' values. We plot the 'before' data as a line, then plot the 'after' data on the same graph. Adding a legend labels each line for clarity. Finally, plt.show() displays the plot window so we can see the comparison visually. This step-by-step trace helps beginners understand how each command changes the plot state and why the order matters.

Practice

(1/5)
1. What is the main purpose of a before-after comparison plot in matplotlib?
easy
A. To visually compare data from two different time points
B. To show the distribution of a single dataset
C. To display the correlation between two variables
D. To create a 3D surface plot

Solution

  1. Step 1: Understand the concept of before-after plots

    Before-after plots are used to compare data points from two different times or conditions to see changes.
  2. Step 2: Identify the correct purpose

    Among the options, only To visually compare data from two different time points describes comparing data from two time points, which matches the before-after plot purpose.
  3. Final Answer:

    To visually compare data from two different time points -> Option A
  4. Quick Check:

    Before-after plots = compare two time points [OK]
Hint: Before-after plots compare two sets of data visually [OK]
Common Mistakes:
  • Confusing before-after plots with distribution plots
  • Thinking they show correlation instead of change
  • Assuming they create 3D plots
2. Which of the following is the correct way to plot two sets of data side-by-side for before-after comparison using matplotlib?
easy
A. plt.plot(before_data); plt.plot(after_data)
B. plt.bar([0,1], before_data); plt.bar([0,1], after_data)
C. plt.bar([0,1], before_data); plt.bar([1,2], after_data)
D. plt.bar([1,2], [before_data, after_data])

Solution

  1. Step 1: Understand bar plot positioning

    To show before and after side-by-side, bars must not overlap. Using different x positions for before and after data avoids overlap.
  2. Step 2: Analyze options for correct bar positions

    plt.bar([0,1], before_data); plt.bar([1,2], after_data) places before_data at positions 0 and 1, and after_data at 1 and 2, so bars for the same category are side-by-side without overlap.
  3. Final Answer:

    plt.bar([0,1], before_data); plt.bar([1,2], after_data) -> Option C
  4. Quick Check:

    Side-by-side bars need different x positions [OK]
Hint: Use different x positions to avoid bar overlap [OK]
Common Mistakes:
  • Plotting bars at same x positions causing overlap
  • Using plt.plot instead of plt.bar for categorical data
  • Passing data incorrectly as list of lists
3. What will be the output of this code snippet?
import matplotlib.pyplot as plt
before = [5, 7]
after = [8, 6]
plt.plot([1, 2], before, label='Before')
plt.plot([1, 2], after, label='After')
plt.legend()
plt.show()
medium
A. An error because plt.plot cannot take two lists
B. A bar chart comparing before and after data
C. A scatter plot with points at (1,5), (2,7), (1,8), (2,6)
D. Two overlapping line plots showing before and after data

Solution

  1. Step 1: Understand plt.plot with x and y lists

    plt.plot([1, 2], before) plots points (1,5) and (2,7) connected by a line. Similarly for after data.
  2. Step 2: Identify plot type and legend

    Two line plots will appear overlapping on the same axes with labels 'Before' and 'After'. No error occurs.
  3. Final Answer:

    Two overlapping line plots showing before and after data -> Option D
  4. Quick Check:

    plt.plot with x,y lists = line plot [OK]
Hint: plt.plot(x, y) draws lines connecting points [OK]
Common Mistakes:
  • Thinking plt.plot creates bar charts
  • Expecting scatter plot without plt.scatter
  • Assuming plt.plot with two lists causes error
4. Identify the error in this code for before-after bar plot:
import matplotlib.pyplot as plt
before = [3, 4]
after = [5, 6]
plt.bar([0, 1], before)
plt.bar([0, 1], after)
plt.show()
medium
A. plt.show() is missing
B. Bars for before and after overlap at same positions
C. before and after lists must be same length
D. plt.bar requires three arguments

Solution

  1. Step 1: Check bar positions

    Both before and after bars are plotted at positions 0 and 1, causing them to overlap and hide one another.
  2. Step 2: Identify correct fix

    To avoid overlap, after bars should be shifted to different x positions, e.g., [0.3, 1.3].
  3. Final Answer:

    Bars for before and after overlap at same positions -> Option B
  4. Quick Check:

    Same x positions cause bar overlap [OK]
Hint: Shift bars on x-axis to avoid overlap [OK]
Common Mistakes:
  • Thinking plt.bar needs 3 arguments
  • Ignoring bar overlap issue
  • Assuming plt.show() is missing
5. You have sales data before and after a marketing campaign for 3 products: before = [100, 150, 200], after = [120, 180, 210]. How would you create a clear before-after bar plot with labels and legend in matplotlib?
hard
A. Use plt.bar with shifted x positions for before and after, add labels and legend
B. Plot before and after using plt.plot without labels
C. Use plt.scatter for both datasets on same x positions
D. Plot only after data as a bar chart

Solution

  1. Step 1: Plan bar positions and labels

    To compare before and after clearly, plot bars side-by-side with shifted x positions, e.g., before at [0,1,2], after at [0.3,1.3,2.3]. Add x-axis labels for products.
  2. Step 2: Add legend and labels for clarity

    Use plt.legend() to distinguish before and after bars, and plt.xlabel/plt.ylabel for axis labels.
  3. Final Answer:

    Use plt.bar with shifted x positions for before and after, add labels and legend -> Option A
  4. Quick Check:

    Shift bars + labels + legend = clear before-after plot [OK]
Hint: Shift bars and add legend for clear comparison [OK]
Common Mistakes:
  • Plotting bars at same positions causing confusion
  • Skipping labels and legend
  • Using scatter plot instead of bar plot