Bird
Raised Fist0
Matplotlibdata~20 mins

Trend lines on scatter plots in Matplotlib - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Trend Line Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of scatter plot with linear trend line
What will be the output of this code snippet that plots a scatter plot and adds a linear trend line?
Matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 5, 4, 5])

plt.scatter(x, y)
coeffs = np.polyfit(x, y, 1)
trend = np.poly1d(coeffs)
plt.plot(x, trend(x), color='red')
plt.show()
AA scatter plot with points at (1,2), (2,4), (3,5), (4,4), (5,5) and a red straight line roughly fitting the points.
BA scatter plot with points and a blue curved line that passes through all points exactly.
CA scatter plot with points but no line is drawn.
DA scatter plot with points and a green horizontal line at y=3.
Attempts:
2 left
💡 Hint
Look at how np.polyfit with degree 1 creates a straight line fit.
❓ data_output
intermediate
1:30remaining
Number of points above the trend line
Given the following data and trend line, how many points lie above the linear trend line?
Matplotlib
import numpy as np

x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 5, 4, 5])
coeffs = np.polyfit(x, y, 1)
trend = np.poly1d(coeffs)
points_above = sum(y > trend(x))
print(points_above)
A4
B3
C1
D2
Attempts:
2 left
💡 Hint
Compare each y value to the trend line value at the same x.
❓ visualization
advanced
2:30remaining
Identify the correct polynomial trend line plot
Which option shows the correct plot of a scatter plot with a quadratic (degree 2) trend line for the data below?
Matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4, 5])
y = np.array([1, 4, 9, 16, 25])

plt.scatter(x, y)
coeffs = np.polyfit(x, y, 2)
trend = np.poly1d(coeffs)
plt.plot(x, trend(x), color='green')
plt.show()
AScatter points forming a perfect square curve with a green curved line passing exactly through all points.
BScatter points with a green straight line that does not fit the curve well.
CScatter points with a green curved line that misses all points.
DScatter points with a green horizontal line at y=10.
Attempts:
2 left
💡 Hint
Degree 2 polynomial fits a parabola shape.
🔧 Debug
advanced
2:00remaining
Identify the error in trend line code
What error will this code raise when trying to plot a trend line on a scatter plot?
Matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 3, 5, 7, 11])

plt.scatter(x, y)
coeffs = np.polyfit(x, y, 1)
trend = np.poly1d(coeffs)
plt.plot(trend(x), x, color='blue')
plt.show()
ATypeError because plt.plot expects x and y arrays but got reversed.
BNo error; the plot shows a blue line but with axes swapped.
CValueError due to mismatched array lengths in plt.plot.
DSyntaxError due to missing parentheses.
Attempts:
2 left
💡 Hint
Check the order of arguments in plt.plot(x, y).
🚀 Application
expert
3:00remaining
Calculate and plot residuals from trend line
Given data points and a linear trend line, which code correctly calculates residuals and plots them as a bar chart?
Matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 3, 5, 7, 11])
coeffs = np.polyfit(x, y, 1)
trend = np.poly1d(coeffs)
residuals = y - trend(x)

plt.bar(x, residuals)
plt.xlabel('x')
plt.ylabel('Residuals')
plt.title('Residuals from Linear Trend Line')
plt.show()
ACalculates residuals as trend(x) - y and plots a line plot instead of bars.
BCalculates residuals as y + trend(x) and plots bars with incorrect values.
CCalculates residuals as y - trend(x) and plots them correctly as bars at each x.
DCalculates residuals as y - trend(x) but plots a scatter plot instead of bars.
Attempts:
2 left
💡 Hint
Residuals are actual minus predicted values and bar plot shows magnitude.

Practice

(1/5)
1. What is the main purpose of adding a trend line to a scatter plot in matplotlib?
easy
A. To show the overall pattern or relationship between variables
B. To add colors to the scatter points
C. To change the size of scatter points
D. To remove outliers from the data

Solution

  1. Step 1: Understand scatter plot purpose

    A scatter plot shows individual data points but may not clearly show the overall trend.
  2. Step 2: Role of trend line

    A trend line summarizes the general direction or pattern in the data, making relationships easier to see.
  3. Final Answer:

    To show the overall pattern or relationship between variables -> Option A
  4. Quick Check:

    Trend line = overall pattern [OK]
Hint: Trend lines summarize data direction, not point details [OK]
Common Mistakes:
  • Thinking trend lines change point colors
  • Confusing trend lines with point size changes
  • Believing trend lines remove data points
2. Which of the following code snippets correctly fits a linear trend line to data arrays x and y using numpy?
easy
A. coefficients = np.polyfit(x, y, 1)
B. coefficients = np.polyfit(y, x, 1)
C. coefficients = np.polyfit(x, y, 2)
D. coefficients = np.polyfit(x, y)

Solution

  1. Step 1: Understand np.polyfit parameters

    np.polyfit(x, y, degree) fits a polynomial of given degree to x and y data.
  2. Step 2: Correct usage for linear fit

    For a linear trend line, degree = 1, and x is independent variable, y is dependent variable.
  3. Final Answer:

    coefficients = np.polyfit(x, y, 1) -> Option A
  4. Quick Check:

    np.polyfit(x, y, 1) fits linear trend [OK]
Hint: Use degree=1 for linear trend with np.polyfit(x, y, 1) [OK]
Common Mistakes:
  • Swapping x and y in np.polyfit
  • Omitting degree parameter
  • Using degree 2 for linear trend
3. Given the code below, what will be the output of print(trendline(3))?
import numpy as np
x = np.array([1, 2, 3, 4])
y = np.array([2, 4, 6, 8])
coefficients = np.polyfit(x, y, 1)
trendline = np.poly1d(coefficients)
print(trendline(3))
medium
A. Error due to incorrect polyfit usage
B. 5.0
C. 9.0
D. 6.0

Solution

  1. Step 1: Analyze data and polyfit

    Data y doubles x (2,4,6,8), so linear fit slope ~2 and intercept ~0.
  2. Step 2: Calculate trendline at x=3

    trendline(3) = 2*3 + 0 = 6.0
  3. Final Answer:

    6.0 -> Option D
  4. Quick Check:

    trendline(3) = 6.0 [OK]
Hint: Check if y is roughly 2*x; then trendline(3) = 6 [OK]
Common Mistakes:
  • Confusing x and y order in polyfit
  • Forgetting poly1d creates function
  • Assuming error instead of numeric output
4. Identify the error in the following code that tries to plot a scatter plot with a trend line:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([1, 2, 3, 4])
y = np.array([2, 3, 5, 7])
coeff = np.polyfit(x, y, 1)
trend = np.poly1d(coeff)
plt.scatter(x, y)
plt.plot(x, trend)
plt.show()
medium
A. np.polyfit arguments are in wrong order
B. plt.plot(x, trend) should be plt.plot(x, trend(x))
C. plt.scatter should be called after plt.plot
D. Missing plt.xlabel and plt.ylabel calls

Solution

  1. Step 1: Check trend line plotting

    plt.plot expects y-values, but trend is a function, not values.
  2. Step 2: Correct function call

    Call trend(x) to get y-values for plotting: plt.plot(x, trend(x))
  3. Final Answer:

    plt.plot(x, trend) should be plt.plot(x, trend(x)) -> Option B
  4. Quick Check:

    Plot function needs y-values, not function [OK]
Hint: Call trend(x) to get y-values for plt.plot [OK]
Common Mistakes:
  • Passing function instead of values to plt.plot
  • Swapping x and y in polyfit
  • Thinking plot order affects output
  • Missing axis labels is not an error
5. You have noisy data with outliers. Which approach best improves the trend line fit on a scatter plot using matplotlib and numpy?
hard
A. Plot scatter without trend line to avoid confusion
B. Use np.polyfit with degree 1 on all data points
C. Remove outliers before fitting trend line with np.polyfit
D. Use plt.plot instead of plt.scatter for all points

Solution

  1. Step 1: Understand effect of outliers

    Outliers can distort the trend line fit, making it less representative.
  2. Step 2: Improve fit by removing outliers

    Removing or filtering outliers before fitting helps get a better trend line.
  3. Final Answer:

    Remove outliers before fitting trend line with np.polyfit -> Option C
  4. Quick Check:

    Remove outliers for better trend line [OK]
Hint: Filter outliers before fitting trend line for accuracy [OK]
Common Mistakes:
  • Fitting trend line on all data including outliers
  • Skipping trend line when data is noisy
  • Confusing plot types for trend line fitting
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