我试图通过创建一个要求输入“顺序”的 x 函数来绘制带有 R 的系列的第 n 阶。
像这样的东西,但这对任意 x 不起作用,它返回错误:找不到对象“x”。
fun1 <- function(order,x) {
output = 0
for (i in 0:order){
output = output + ((-1)**order)*((x**(2)/factorial(2*order))
}
}
plot1 <- ggplot(data = data.frame(x = 0), mapping = aes(x = x)) +
stat_function(fun = fun1(0, x), geom = "line")
理论上这将绘制总和的前导顺序 (-1^order)((x^2)/(2*order)!)
以前我是手工写出系列的每个元素,但是在处理更高的顺序时这很乏味。
编辑:以前工作的一个例子是:
order4 <- function(x) {
(1-((x**2)/2)+((x**2)/24)-((x**2)/720))
}
plot1 <- ggplot(data = data.frame(x = 0), mapping = aes(x = x)) +
stat_function(fun = order4, geom = "line")
让我们修改您的函数,使其更加通用和矢量化:
my_series = function(x, order) {
coefs = (-1)^(0:order) / factorial(2 * (0:order))
x_grid = outer(x, 0:order, "^")
x_grid %*% coefs
}
fun(1:5, order = 3) # looks good
# [,1]
# [1,] 0.5402778
# [2,] 0.1555556
# [3,] -0.1625000
# [4,] -0.4222222
# [5,] -0.6319444
我也把x
论点放在首位,这看起来不错。现在我们可以使用 的args
参数stat_function
来传入order
,如注释中所述。我们为数据框提供了我们想要绘制的 x 值的完整范围。
ggplot(data = data.frame(x = 0:20), mapping = aes(x = x)) +
stat_function(fun = my_series, geom = "line", args = list(order = 3))
对于更高的顺序,这仍然非常快速:
ggplot(data = data.frame(x = -2:280), mapping = aes(x = x)) +
stat_function(fun = my_series, geom = "line", args = list(order = 20))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句