Python绘制带最优拟合直线方程、R²及相关系数的散点图
Solution: Scatter Plot with Fitted Line, Equation, R², and Correlation Coefficient
Got it, let's build this visualization step by step. We'll use pandas for data management, matplotlib for plotting, and scipy.stats to compute the linear regression metrics we need. Here's a complete, ready-to-run implementation:
Step 1: Import Required Libraries
from pandas import DataFrame import matplotlib.pyplot as plt from scipy.stats import linregress
Step 2: Load Your Dataset
data = {'X':[2195,2886,2399,1929,2643,2986,2337,2837,2501,2290,1940,2488,2628,2527,2596,2551,2427,2412,2275,2578,2725,2734,2595,2370,1916,2226,2156,1965], 'Y':[10539,20043,12702,8654,19092,16719,8189,18517,12265,7749,5835,7640,8722,12540,16974 ,11614,7458,7896,7929,8820,8925,7993,8178,7258,5702,9240,9877,5338]} df = DataFrame(data, columns= ['X', 'Y'])
Step 3: Calculate Regression Metrics
We'll use linregress to get the slope, intercept, correlation coefficient (r), and R-squared value in one go:
# Compute linear regression metrics slope, intercept, r_value, p_value, std_err = linregress(df['X'], df['Y']) r_squared = r_value ** 2 # R² is the square of the correlation coefficient
Step 4: Create the Visualization
# Set up plot dimensions plt.figure(figsize=(10, 6)) # Plot raw data points plt.scatter(df['X'], df['Y'], color='steelblue', alpha=0.7, label='Data Points') # Plot the optimal fitted line x_fit = df['X'] y_fit = slope * x_fit + intercept plt.plot(x_fit, y_fit, color='crimson', linewidth=2, label='Optimal Fitted Line') # Add regression details to the plot (adjust position as needed) text_content = (f'Fitted Line: y = {slope:.2f}x + {intercept:.0f}\n' f'Correlation Coefficient (r): {r_value:.4f}\n' f'R²: {r_squared:.4f}') plt.text(df['X'].min() + 50, df['Y'].max() - 1000, text_content, bbox=dict(facecolor='white', alpha=0.8)) # Add plot labels and styling plt.xlabel('X Values', fontsize=12) plt.ylabel('Y Values', fontsize=12) plt.title('Scatter Plot with Optimal Fitted Line', fontsize=14) plt.legend() plt.grid(True, alpha=0.3) # Display the plot plt.show()
Key Notes:
- Correlation Coefficient (
r): Ranges from -1 to 1. A value close to 1 means a strong positive linear relationship, close to -1 means strong negative, and 0 means no linear relationship. - R²: Represents the proportion of variance in Y that's explained by X. A value closer to 1 means the line fits the data better.
- Text Position: The
plt.text()coordinates are set to sit in the top-left area of the plot. Tweak thexandyvalues if you need to move the text box to a different spot. - Customization: Feel free to adjust colors, line widths, or alpha values to match your preferred visual style.
内容的提问来源于stack exchange,提问作者melik
相关产品推荐
相关产品推荐

