如何在ggplot中添加线性判别分析(LDA)线并显示其方程?
在ggplot中绘制LDA的0值决策边界
假设你已经完成了数据创建、基础ggplot绘制和LDA拟合,以下是添加LDA 0值决策线的具体步骤:
1. 提取LDA关键参数
从MASS::lda()的拟合结果里,取LD1的判别系数,以及D、H的总体均值(LDA计算得分时会对变量做中心化处理):
library(MASS) lda_fit <- lda(Group ~ D + H, data = df) # 提取LD1的系数 lda_coef <- lda_fit$scaling[, "LD1"] coef_D <- lda_coef["D"] coef_H <- lda_coef["H"] # 计算D和H的总体均值 mean_vals <- colMeans(df[, c("D", "H")])
2. 定义决策线函数
LDA的0值决策边界对应LD1得分等于0的情况,解这个方程得到H关于D的表达式,写成函数:
lda_decision_line <- function(D) { (-coef_D * (D - mean_vals["D"]) / coef_H) + mean_vals["H"] }
3. 把决策线加到ggplot里
用geom_function()直接绘制这个函数到你的基础散点图上:
library(ggplot2) # 你的基础图(示例) p <- ggplot(df, aes(x = D, y = H, color = Group)) + geom_point() # 添加LDA决策线,样式可自定义 p + geom_function(fun = lda_decision_line, color = "black", linetype = "dashed", linewidth = 1)
可选验证
如果要确认这条线的正确性,可以生成决策线上的点,用predict()计算LD1得分,结果应该接近0:
# 生成测试点 test_points <- data.frame(D = seq(min(df$D), max(df$D), length.out = 5)) test_points$H <- lda_decision_line(test_points$D) # 查看LD1得分 test_scores <- predict(lda_fit, newdata = test_points)$x print(test_scores)
内容的提问来源于stack exchange,提问作者Zard22
相关产品推荐
相关产品推荐

