如何在Julia绘图中添加回归方程与R²系数?
在Julia散点图中添加回归方程与R²系数
要在散点图中添加y=ax+b形式的回归方程和R²系数,只需从拟合好的模型中提取参数,格式化文本后用Plots的标注功能添加即可,具体实现步骤如下:
1. 提取模型参数与R²值
从GLM拟合的线性模型中,直接获取截距、斜率,同时计算或调用函数得到R²:
# 从模型中提取截距和斜率 intercept = coef(model)[1] slope = coef(model)[2] # 获取R²(GLM v1.5+可直接用r2函数,旧版本可手动计算) r_squared = r2(model) # 旧版本手动计算方式:r_squared = 1 - deviance(model)/nulldeviance(model)
2. 格式化文本内容
将参数格式化为易读的y=ax+b方程和R²文本:
# 保留3位小数格式化回归方程 eq_text = "y = $(round(slope, digits=3))x + $(round(intercept, digits=3))" # 保留4位小数格式化R² r2_text = "R² = $(round(r_squared, digits=4))" # 合并为多行文本 annot_text = "$eq_text\n$r2_text"
3. 添加标注到散点图
使用annotate!函数将文本添加到图中合适位置(坐标根据你的数据范围调整):
完整整合代码
using Plots using DataFrames using GLM # 生成数据 df = DataFrame(x = collect(1:7), y = collect(1:7)+rand(7)) # 拟合线性模型 model = lm(@formula(y ~ x), df) # 绘制带平滑线的散点图 scatter(df.x, df.y, smooth = true, label = "data") xlabel!("x") ylabel!("y") # 提取参数与R² intercept = coef(model)[1] slope = coef(model)[2] r_squared = r2(model) # 格式化标注文本 eq_text = "y = $(round(slope, digits=3))x + $(round(intercept, digits=3))" r2_text = "R² = $(round(r_squared, digits=4))" annot_text = "$eq_text\n$r2_text" # 添加标注到图中(示例坐标为x=5, y=8,可根据实际数据调整) annotate!(5, 8, text(annot_text, 10, :left)) # 显示图形 display(current())
注意事项
- 标注的坐标需要根据你的数据范围调整,避免被散点遮挡
- 可通过修改
text函数的参数调整字体大小(示例中为10)、对齐方式(:left/:center/:right)
内容的提问来源于stack exchange,提问作者Quinten
相关产品推荐
相关产品推荐

