1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| import plotly.graph_objects as go from scipy.stats import linregress
def add_plotly_subplot_with_intercept(fig, df, x_col, y_col, row, col, color='blue', show_eq=True): x = df[x_col] y = df[y_col] valid = ~(x.isna() | y.isna()) x = x[valid] y = y[valid]
fig.add_trace(go.Scatter( x=x, y=y, mode='markers', marker=dict(color=color), showlegend=False ), row=row, col=col)
slope, intercept, r_value, _, _ = linregress(x, y) line_x = np.linspace(x.min(), x.max(), 100) line_y = slope * line_x + intercept
fig.add_trace(go.Scatter( x=line_x, y=line_y, mode='lines', line=dict(color='red', dash='dash'), showlegend=False ), row=row, col=col)
if show_eq: eq_text = f"y = {slope:.2f}x + {intercept:.2f}<br>R = {r_value:.2f}" fig.add_annotation( text=eq_text, xref=f'x{col}', yref=f'y{row}', x=x.min() + 0.05 * (x.max() - x.min()), y=y.max() - 0.05 * (y.max() - y.min()), showarrow=False, font=dict(size=11, color="black"), align="left", row=row, col=col )
|
Comments