Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 按面向geom_smooth()提供自定义结值_R_Ggplot2_Tidyverse - Fatal编程技术网

R 按面向geom_smooth()提供自定义结值

R 按面向geom_smooth()提供自定义结值,r,ggplot2,tidyverse,R,Ggplot2,Tidyverse,我正在尝试使用geom_smooth绘制一些分段/断棒回归。例如: ggplot(mtcars, aes(x = mpg, y = hp)) + geom_point() + geom_smooth(method = lm, formula = y ~ splines::bs(x, df = 2, degree = 1, knots = 20)) + facet_wrap(~gear) 但是,这会对每个方面中的断点使用一个值(knots=20)。我希

我正在尝试使用geom_smooth绘制一些分段/断棒回归。例如:

ggplot(mtcars, aes(x = mpg, y = hp)) +
  geom_point() +
  geom_smooth(method = lm, 
              formula = y ~ splines::bs(x, df = 2, degree = 1, knots = 20)) +
  facet_wrap(~gear)

但是,这会对每个方面中的断点使用一个值(knots=20)。我希望为每个方面传递一个唯一的值(我之前已经计算过)。这可能吗

我试着向数据帧中添加一个变量,并传递变量名(例如,
psi
),作为一种美学,但geom_smooth无法识别它。我怀疑答案与定义自定义函数有关,如本页末尾所述:

非常感谢你考虑我的问题

最好的


这似乎是一个棘手的问题。一种解决方案是为每个
档位
使用单独的
geom_平滑
,方法是过滤数据并为
结提供相应的值

在本例中,假设结=档位*4

library(ggplot2)
library(dplyr)

mtcars %>% 
  ggplot(aes(mpg, hp)) +
  geom_point() +
  geom_smooth(data = filter(mtcars, gear == 3),
              method = "lm",
              formula = y ~ splines::bs(x, df = 2, degree = 1, knots = 12)) +
  geom_smooth(data = filter(mtcars, gear == 4),
              method = "lm",
              formula = y ~ splines::bs(x, df = 2, degree = 1, knots = 16)) +
  geom_smooth(data = filter(mtcars, gear == 5),
              method = "lm",
              formula = y ~ splines::bs(x, df = 2, degree = 1, knots = 20)) +
  facet_wrap(~gear)
结果: