Plot a polynomial function like on the wolframalpha-website so that it is easy to understand

倖福魔咒の 提交于 2019-12-22 05:41:17

问题


Plotting a function in the wolfram-alpha-website looks like this:

http://www.wolframalpha.com/link

Plotting the same function in R looks like this:

plot( function(x) x^2 - 3*x - 10 )

The default plot from Wolfram is much easier to understand. I think this is because it shows the x-axis (at y=0), and centers the parabola.

I am not good enough at math to just look at the formula of a function and see where I should center the plot, and I am plotting the functions to learn about how different functions create different lines, so I need this centering to be done automatically, because otherwise I might misunderstand a plot.

Is it possible to create the Wolfram-plot automatically i.e. without me telling R where it would be sensible to center the plot?


回答1:


The polynom package will create some sensible defaults.

eg.

library(polynom)

# your polynomial (coefficients in ascending powers of x order)
p <- polynomial(c(-10,-3,1))
plot(p)

 # a more complicated example, a polynomial crossing the x axis at -1,0,1,2,3,4,5

 p2 <- poly.calc(-1:5)
 p2 
 # -120*x + 154*x^2 + 49*x^3 - 140*x^4 + 70*x^5 - 14*x^6 + x^7 
 plot(p2)




回答2:


You can set the desired interval to plot over, as described in ?plot.function. Also see curve and abline.

plot( function(x) x^2 - 3*x - 10 , -15, 15) ; abline(h=0,v=0,lty=3)

or

curve(x^2 - 3*x - 10 , -15, 15) ; abline(h=0,v=0,lty=3)



回答3:


This is quite an old post post but I was trying to fit a polynomial curve based on the coefficients of my model.

The original in base R :

plot( y ~ x) 
curve(3*x - 2*x^2 + 2*x^3)   ##  random coefficients for easy example 

I use ggplot2 - so I wanted to use the curve generated from the coefficients rather than a + geom_smooth (This also works but I prefer the curve below)

bestfit <- geom_smooth(method = "loess", se = T, size = 1) 

ggplot2 
+ bestfit

Instead I created a function with the coefficients above

test 
test <- function(x) {3*x - 2*x^2 + 2*x^3} 

I have then added it as a layer in the ggplot

ggplot2
+ stat_function(fun = test)

It gives me the same curve as the base plot function but I can add all the additional layers in ggplot



来源:https://stackoverflow.com/questions/20251653/plot-a-polynomial-function-like-on-the-wolframalpha-website-so-that-it-is-easy-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!