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

使用stat_poly_eq展示sqrt(y)~asin(sqrt(x))关系时方程不显示问题

解决stat_poly_eq无法展示转换后回归方程的问题

问题分析

当使用geom_smooth拟合sqrt(y) ~ asin(sqrt(x))形式的模型时,拟合线能正常生成,但stat_poly_eq无法展示回归方程并抛出计算失败警告,核心原因是stat_poly_eq默认适配y ~ x类的标准多项式拟合,无法自动识别变量转换后的公式结构。

解决方案

方法1:调整stat_poly_eq参数适配转换公式

通过指定eq.with.lhs明确方程左侧的转换形式,让stat_poly_eq正确解析拟合结果:

首先确保加载依赖包:

library(ggplot2)
library(ggpmisc)

数据集代码:

require(utils)
x = runif(n = 10, min = 0.2, max = 1)
y = rnorm(n = 10, mean = 2.5, sd = .5)
df = expand.grid(x = x, y = y)

修正后的绘图代码:

ggplot(df , aes(x = x, y = y)) +
  geom_point() +
  geom_smooth(method = "lm", se = TRUE, formula = sqrt(y) ~ asin(sqrt(x)), col = "black") +
  stat_poly_eq(
    aes(label = after_stat(eq.label)), 
    formula = sqrt(y) ~ asin(sqrt(x)),
    eq.with.lhs = "sqrt(y)~`=`~",
    parse = TRUE
  )

方法2:用stat_fit_tidy自定义回归方程标签

如果需要展示原变量y的表达式(而非转换后的sqrt(y)),可以通过stat_fit_tidy提取拟合系数,手动构建方程:

ggplot(df , aes(x = x, y = y)) +
  geom_point() +
  geom_smooth(method = "lm", se = TRUE, formula = sqrt(y) ~ asin(sqrt(x)), col = "black") +
  stat_fit_tidy(
    aes(label = sprintf("y~`=`~(%.2f*asin(sqrt(x))+%.2f)^2", after_stat(estimate)[2], after_stat(estimate)[1])),
    formula = sqrt(y) ~ asin(sqrt(x)),
    parse = TRUE
  )

额外注意事项

  • 确保ggpmisc包为最新版本,旧版本对非标准拟合公式的支持有限;
  • 两种方法都需要设置parse = TRUE,让ggplot解析LaTeX格式的数学表达式。

内容的提问来源于stack exchange,提问作者hnguyen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 21:27:35