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

使用stat_smooth时出现‘object 'm' not found’错误,求解决方法

解决stat_smooth中无法引用数据框行数的问题

错误原因

你通过mutate(m=n())将数据集行数添加为数据列,但stat_smooth的n参数属于图层的全局参数,并非aes()映射的一部分,它不会从数据框的环境中读取变量,因此会提示找不到m对象。

解决方法

方法1:提前存储行数到变量

先获取数据集的行数并存储为独立变量,再在stat_smooth中直接引用该变量:

data <- tibble(x=runif(20), y=runif(20))
n_rows <- nrow(data) # 提前获取行数

data %>% 
  ggplot() + 
  geom_point(aes(x = x, y = y), colour = 'red') +
  geom_smooth(aes(x = x, y = y), method = NULL, se = TRUE) +
  stat_smooth(aes(x = x, y = x), n = n_rows)

方法2:在stat_smooth中直接调用nrow(.)

利用管道传递的数据上下文,直接在n参数中调用nrow(.)获取当前数据集的行数:

data <- tibble(x=runif(20), y=runif(20))

data %>% 
  ggplot() + 
  geom_point(aes(x = x, y = y), colour = 'red') +
  geom_smooth(aes(x = x, y = y), method = NULL, se = TRUE) +
  stat_smooth(aes(x = x, y = x), n = nrow(.))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 06:02:37