Trend lines help us see the general direction or pattern in scattered data points. They make it easier to understand relationships between two variables.
Trend lines on scatter plots in Matplotlib
import numpy as np import matplotlib.pyplot as plt # Create scatter plot plt.scatter(x, y) # Calculate trend line coefficients coefficients = np.polyfit(x, y, degree) # Create polynomial function from coefficients poly_fn = np.poly1d(coefficients) # Plot trend line plt.plot(x, poly_fn(x), color='red') plt.show()
Use np.polyfit to find the best fit line or curve. The degree is usually 1 for a straight line.
np.poly1d creates a function you can use to get y-values for any x.
import numpy as np import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [2, 3, 5, 7, 11] plt.scatter(x, y) coefficients = np.polyfit(x, y, 1) poly_fn = np.poly1d(coefficients) plt.plot(x, poly_fn(x), color='red') plt.show()
import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 10, 50) y = np.sin(x) + np.random.normal(0, 0.2, 50) plt.scatter(x, y) coefficients = np.polyfit(x, y, 3) # cubic trend line poly_fn = np.poly1d(coefficients) plt.plot(x, poly_fn(x), color='green') plt.show()
This program creates a scatter plot of points and draws a red straight trend line showing the general upward trend.
import numpy as np import matplotlib.pyplot as plt # Sample data x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) y = np.array([2.3, 2.9, 3.8, 4.5, 5.1, 5.8, 6.5, 7.1, 7.9, 8.4]) # Scatter plot plt.scatter(x, y, label='Data points') # Calculate linear trend line coefficients = np.polyfit(x, y, 1) # degree 1 for straight line poly_fn = np.poly1d(coefficients) # Plot trend line plt.plot(x, poly_fn(x), color='red', label='Trend line') # Add labels and legend plt.xlabel('X values') plt.ylabel('Y values') plt.title('Scatter Plot with Trend Line') plt.legend() plt.grid(True) plt.show()
Make sure your x values are sorted or use np.sort(x) before plotting the trend line for a smooth line.
Higher degree polynomials can fit data better but may cause wiggly lines that overfit.
Always label your plots to make them easy to understand.
Trend lines show the overall direction in scattered data.
Use np.polyfit and np.poly1d to create trend lines.
Plot the trend line on top of scatter points to visualize relationships.
Practice
Solution
Step 1: Understand scatter plot purpose
A scatter plot shows individual data points but may not clearly show the overall trend.Step 2: Role of trend line
A trend line summarizes the general direction or pattern in the data, making relationships easier to see.Final Answer:
To show the overall pattern or relationship between variables -> Option AQuick Check:
Trend line = overall pattern [OK]
- Thinking trend lines change point colors
- Confusing trend lines with point size changes
- Believing trend lines remove data points
x and y using numpy?Solution
Step 1: Understand np.polyfit parameters
np.polyfit(x, y, degree) fits a polynomial of given degree to x and y data.Step 2: Correct usage for linear fit
For a linear trend line, degree = 1, and x is independent variable, y is dependent variable.Final Answer:
coefficients = np.polyfit(x, y, 1) -> Option AQuick Check:
np.polyfit(x, y, 1) fits linear trend [OK]
- Swapping x and y in np.polyfit
- Omitting degree parameter
- Using degree 2 for linear trend
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))
Solution
Step 1: Analyze data and polyfit
Data y doubles x (2,4,6,8), so linear fit slope ~2 and intercept ~0.Step 2: Calculate trendline at x=3
trendline(3) = 2*3 + 0 = 6.0Final Answer:
6.0 -> Option DQuick Check:
trendline(3) = 6.0 [OK]
- Confusing x and y order in polyfit
- Forgetting poly1d creates function
- Assuming error instead of numeric output
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()
Solution
Step 1: Check trend line plotting
plt.plot expects y-values, but trend is a function, not values.Step 2: Correct function call
Call trend(x) to get y-values for plotting: plt.plot(x, trend(x))Final Answer:
plt.plot(x, trend) should be plt.plot(x, trend(x)) -> Option BQuick Check:
Plot function needs y-values, not function [OK]
- 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
Solution
Step 1: Understand effect of outliers
Outliers can distort the trend line fit, making it less representative.Step 2: Improve fit by removing outliers
Removing or filtering outliers before fitting helps get a better trend line.Final Answer:
Remove outliers before fitting trend line with np.polyfit -> Option CQuick Check:
Remove outliers for better trend line [OK]
- Fitting trend line on all data including outliers
- Skipping trend line when data is noisy
- Confusing plot types for trend line fitting
Ready to prove it?
Pass the test and this pattern moves unknown
