如何绘制StatsModels多元OLS回归图并获取各变量与ERP4M的相关性
Got it, let's break down your needs into two clear parts—first calculating the correlations between each variable and ERP4M, then exploring dedicated libraries and methods to visualize your OLS regression results beautifully.
Using pandas, you can easily extract and sort the correlation coefficients for all variables against ERP4M. Here's a straightforward implementation:
import pandas as pd # Assume your dataset is stored in a DataFrame called `df` # Calculate pairwise correlations and isolate ERP4M's column corr_with_erp4m = df.corr()['ERP4M'].sort_values(ascending=False) # Convert to a DataFrame for cleaner viewing corr_df = corr_with_erp4m.to_frame(name='Correlation with ERP4M') # Print or inspect the result print(corr_df)
This will give you a sorted list of Pearson correlation coefficients, making it easy to see which variables have the strongest linear relationships with ERP4M.
There are several dedicated libraries and tools to create polished regression visualizations. Let's cover the most reliable options:
2.1 Statsmodels (Built-in Regression Visualization)
Statsmodels is the go-to library for OLS modeling in Python, and it includes built-in functions for regression diagnostics and visualization.
Example 1: Single Predictor Regression Diagnostics
This plot shows the relationship between a predictor and ERP4M, along with residuals and other diagnostic metrics:
import statsmodels.api as sm import matplotlib.pyplot as plt # First, fit your OLS model X = df.drop('ERP4M', axis=1) X = sm.add_constant(X) # Add intercept term y = df['ERP4M'] model = sm.OLS(y, X).fit() # Generate diagnostic plots for a specific predictor (e.g., 'Variable1') fig = sm.graphics.plot_regress_exog(model, 'Variable1') fig.tight_layout() plt.show()
Example 2: Coefficient Bar Plot with Confidence Intervals
This is a great way to visualize the magnitude and significance of each predictor's effect:
# Extract coefficients and confidence intervals into a DataFrame coef_df = pd.DataFrame({ 'Coefficient': model.params, 'Lower 95% CI': model.conf_int()[0], 'Upper 95% CI': model.conf_int()[1] }) # Drop the intercept term if you don't want to display it coef_df = coef_df.drop('const') # Plot plt.figure(figsize=(10, 6)) coef_df['Coefficient'].plot( kind='bar', yerr=[ coef_df['Coefficient'] - coef_df['Lower 95% CI'], coef_df['Upper 95% CI'] - coef_df['Coefficient'] ], capsize=5, color='#1f77b4' ) plt.title('OLS Regression Coefficients (95% Confidence Intervals)') plt.ylabel('Coefficient Value') plt.axhline(y=0, color='red', linestyle='--') # Highlight zero line for significance plt.xticks(rotation=45) plt.show()
2.2 Seaborn (Clean, Statistical Visualizations)
Seaborn simplifies creating aesthetically pleasing regression plots, especially for exploring individual predictor relationships:
import seaborn as sns # Plot a single predictor vs ERP4M with regression line and confidence interval sns.lmplot(x='Variable1', y='ERP4M', data=df, ci=95, line_kws={'color': 'red'}) plt.title('ERP4M vs Variable1 (OLS Regression Fit)') plt.show() # Plot all predictors against ERP4M at once (great for quick exploration) sns.pairplot( df, x_vars=df.columns.drop('ERP4M'), y_vars=['ERP4M'], kind='reg', ci=95, plot_kws={'line_kws': {'color': 'red'}} ) plt.suptitle('ERP4M vs All Predictors (OLS Regression Fits)', y=1.02) plt.show()
2.3 Plotly (Interactive Visualizations)
If you want interactive plots (e.g., hover to see exact values, zoom), Plotly is perfect:
import plotly.express as px # Convert coefficient DataFrame for Plotly coef_df_plotly = coef_df.reset_index().rename(columns={'index': 'Variable'}) # Create interactive coefficient bar plot fig = px.bar( coef_df_plotly, x='Variable', y='Coefficient', error_y='Lower 95% CI', error_y_minus='Upper 95% CI', title='OLS Regression Coefficients (95% Confidence Intervals)', color='Coefficient', color_continuous_scale='RdBu' ) fig.add_hline(y=0, line_dash='dash', line_color='black') fig.update_layout(xaxis_tickangle=-45) fig.show()
Quick Troubleshooting Tip
If your previous attempts failed, double-check:
- Did you include an intercept term in your OLS model? (Statsmodels doesn't add this by default)
- Are there missing values or outliers in your data that might be breaking plots?
- Did you correctly extract the model parameters (e.g.,
model.paramsinstead of a wrong attribute)?
内容的提问来源于stack exchange,提问作者Évariste Galois

