使用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
相关产品推荐
相关产品推荐

