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

使用ggpmisc在RStudio绘制线性回归方程时遇错误的解决咨询

解决ggpmisc绘制dc组回归方程时的报错问题

问题现象

使用ggpmisc包(v0.5.3)绘制线性回归曲线并展示回归方程与R²值时,dd组数据代码正常运行,但dc组数据触发报错:

Computation failed in stat_poly_eq()
Caused by error in check_output():
! out[1] <= out[2] is not TRUE

同时伴随警告:

In ci_f_ncp(stat, df1 = df1, df2 = df2, probs = probs) :
Upper limit outside search range. Set to the maximum of the parameter range.

报错原因

dc组中部分ch分组的线性回归模型拟合度极差,R²可能接近0甚至为负,导致stat_poly_eq()在计算统计量置信区间时出现数值异常——统计量的上下限顺序混乱,触发out[1] <= out[2]的检查逻辑失败。

解决办法

1. 先排查分组模型拟合情况

先确认dc组各分组的回归结果,找出拟合异常的分组:

# 检查dc组每个ch分组的回归指标
d_f_tf1_dc %>%
  group_by(ch) %>%
  do(model = lm(fou ~ dt, data = .)) %>%
  mutate(glance_model = map(model, glance)) %>%
  unnest(glance_model) %>%
  select(ch, r.squared, adj.r.squared, p.value)

2. 修改绘图参数跳过异常计算

如果不需要置信区间,可通过ci=FALSE关闭相关计算,避免数值异常;同时添加rr.digits统一R²的显示格式:

p_14= ggplot(data=d_f_tf1_dc, aes(dt, fou, color= ch)) + 
  geom_smooth(method="lm", se=F, linewidth= 1, aes(linetype= ch, colour= ch, group= ch))+ 
  geom_point(aes(colour= ch, shape= ch), size= 3.5, alpha= .8) + 
  stat_poly_eq( 
    formula= y~x, 
    aes(label = paste(after_stat(eq.label), 
                      after_stat(rr.label), 
                      sep = "*plain(; )~~")), 
    label.x = "right", label.y = "bottom", hjust="inward", 
    coef.digits = 3, 
    rr.digits = 3,  # 统一R²小数位数
    size=4, 
    vstep= 0.05, 
    ci = FALSE,  # 关闭置信区间计算
    parse=T) 
p_14

3. 筛选有效分组后绘图

如果需要保留置信区间,可先筛选出R²大于0的分组再绘图:

# 筛选R²>0的有效分组
valid_groups <- d_f_tf1_dc %>%
  group_by(ch) %>%
  do(model = lm(fou ~ dt, data = .)) %>%
  mutate(r2 = glance(model)$r.squared) %>%
  filter(r2 > 0) %>%
  pull(ch)

# 仅绘制有效分组的回归曲线与方程
p_14_filtered= ggplot(data=d_f_tf1_dc %>% filter(ch %in% valid_groups), aes(dt, fou, color= ch)) + 
  geom_smooth(method="lm", se=F, linewidth= 1, aes(linetype= ch, colour= ch, group= ch))+ 
  geom_point(aes(colour= ch, shape= ch), size= 3.5, alpha= .8) + 
  stat_poly_eq( 
    formula= y~x, 
    aes(label = paste(after_stat(eq.label), 
                      after_stat(rr.label), 
                      sep = "*plain(; )~~")), 
    label.x = "right", label.y = "bottom", hjust="inward", 
    coef.digits = 3, 
    rr.digits = 3,
    size=4, 
    vstep= 0.05, 
    parse=T) 
p_14_filtered

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 07:55:02