2022-03-08
I want to plot a high degree polynomial function with given coefficients.I created this functionf_erzeuger()
is for writing a polynomial functionf
to be able to use ggplot2 and stat_function(fun=f)
.coef
is the coefficient vector of the polynomial function.
f_erzeuger <- function(coef) {
f <- function(x) {
x_vec <- c(1, x, span> x^2, x^3, span> x^4, x^5, span> x^6, x^7, span> x^8, x^9, span> x^10)
d <- length(coef) - 1 # degree of the polynomial
sum(coef * x_vec[1: (d 1)])
}
f
}
But ggplot2 cannot draw this curve, probably because the function doesn’t actually compute the function term.
f <- f_erzeuger(c(4 , 5, 2))
ggplot(data.frame(x = c(-50, 50)), aes(x = x))
stat_function(fun = f, color = "blue")
stat_function(fun = function(x){3 5*x 2*x^2}, color = "red")
f
shows up as a constant line even though it should be polynomial.
uj5u.com enthusiastic netizens replied:
The problem is that your function is not vectorized.run?stat_function
and view the following filesfun
:
In order to vectorize the function, we need to ensure that, for example, f(c(0, 1))
will returnc(f(0), f(1))
.Note that a problem in your function is the line you define x_vec=c(1, x,...)
.ifx
is a vector with multiple elements, this will not work.
There are many ways to vectorize your functions.I will use the tidyverse (mostly purrr::map()
)to do this.
f_erzeuger = function(coef) {
function(xvals) {
d = length(coef)
map_dbl(xvals, function(x) {
x_vec = x ^ (0:( d - 1))
sum(coef * x_vec)
})
}
}
Changes to this feature:
- On top of that, the function is now vectorized.
x_vec
We can use^
R vectorization in (sox^(0:2)
same asc(1, x, x^2)
) the fact that instead of font>explicitdefine10 order.- We can return the function directly inside,
f_erzeuger()
instead of definingf
then pass it back.
Now things will work as expected:
f <- f_erzeuger(c(4 , 5, 2))
ggplot(data.frame(x = c(-50, 50)), aes(x = x))
stat_function(fun = f, color = "blue")
stat_function(fun = function(x){3 5*x 2*x^2}, color = "red")
uj5u.com enthusiastic netizens replied:
trycurve
.
f <- f_erzeuger(c(4 , 5, 2))
curve(Vectorize(f)(x), span> -50, 50, col='#c55d0d')
Read more here: Source link