You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为带Lowess趋势线的Plotly散点图添加R²(决定系数)

为Plotly Lowess趋势线散点图添加R²系数

由于Plotly Express的trendline='lowess'没有直接提供自动添加R²的内置函数,你可以通过以下两种方式实现需求:

方法一:自动计算R²并添加到趋势线末端

通过提取趋势线拟合结果计算R²,再将标注添加到趋势线右下角:

修改后的完整代码

import plotly.express as px
from plotly.subplots import make_subplots
import plotly.graph_objects as go
from sklearn.metrics import r2_score  # 用于计算R²

color_map = {'PORTUGAL': 'green', 'FRANCIA': 'royalblue', 'REINO UNIDO': 'lightgray', 'BELGICA': 'red'}

fig = px.scatter(df_datos, x="EAD", y="RAR", size="Margen_bruto", color="País", color_discrete_map=color_map, hover_name="Cliente", hover_data={'País':True, 'EAD':':.0f', 'RAR':':.0%', 'Margen_bruto':':.0f'}, size_max=30, trendline='lowess', trendline_color_override='black', trendline_scope='overall', title="dic 2021 - 219 clientes")

# 添加参考线
fig.add_hline(y=0.13, line_dash="solid", line_color="orange", annotation_text="13% RAR", annotation_position="bottom right", annotation_font_color="orange")
fig.add_vline(x=33452378, line_dash="dash", line_color="orange", annotation_text="50% EAD", annotation_position="top right", annotation_font_color="orange")
fig.add_vline(x=97227035, line_dash="dot", line_color="orange", annotation_text="80% EAD", annotation_position="top right", annotation_font_color="orange")

# 获取Lowess趋势线数据
trendline_trace = fig.data[-1]
end_x = trendline_trace.x[-1]
end_y = trendline_trace.y[-1]

# 计算R²值
y_true = df_datos['RAR']
y_pred = px.get_trendline_results(fig).iloc[0].px_fitted_results.predict(df_datos['EAD'])
r2_value = r2_score(y_true, y_pred)
r2_label = f"R² = {r2_value:.4f}"

# 添加R²标注到趋势线末端
fig.add_annotation(
    x=end_x,
    y=end_y,
    text=r2_label,
    showarrow=False,
    font=dict(color='black', size=12),
    xshift=10,  # 水平偏移避免遮挡趋势线
    yshift=5    # 垂直偏移调整位置
)

fig.show()

方法二:手动指定R²值添加标注

如果你已经自行算出R²,直接跳过计算步骤,添加标注即可:

关键代码片段

# 替换为你已计算好的R²值
r2_label = "R² = 0.1234"

# 获取趋势线末端坐标
trendline_trace = fig.data[-1]
end_x = trendline_trace.x[-1]
end_y = trendline_trace.y[-1]

# 添加标注
fig.add_annotation(
    x=end_x,
    y=end_y,
    text=r2_label,
    showarrow=False,
    font=dict(color='black', size=12),
    xshift=10,
    yshift=5
)

效果说明

添加后的标注会显示在Lowess趋势线的右下角末端,与趋势线颜色一致(黑色),不会遮挡散点或参考线。

内容的提问来源于stack exchange,提问作者PAULA CANOSA RAMOS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 23:25:17