Phlox Midas
Phlox Midas

Reputation: 4349

Adding more points on a polynomial curve

I'm trying to draw the curve of a polynomial but there are so few points that the curve looks really straight at some places. How can I test more points on the polynomial so I'll have a nicer curve? Picture illustrating problem below with code attempting to solve problem.

enter image description here

library('MonoPoly') # monotonic polynomials

dataT = read.csv("data.csv", header=TRUE, sep=",")
x <- dataT[,'x']
y <- dataT[,'y']
fitResult <- monpol(y~x, degree=3,algorithm="Hawkins")
fitted <- fitted(fitResult) # not enough data points. Only 120

z = predict(fitResult, seq(1, 5, 0.01)) # attempt at making more data points

plot(1:5, 1:5, type = "n")# setting up coord system
points(x,y,col="red") # plotting data fitting to
lines(sort(x), sort(fitted),col="blue") #plotting fitted because z isn't working
points(x,z,col="blue") # plotting curve

Upvotes: 1

Views: 66

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226097

You haven't given a reproducible example, but in general to the answer to this sort of question is that most predict() methods in R have a newdata argument that allows prediction with additional points.

library('MonoPoly') # monotonic polynomials

Set up data:

set.seed(101)
dd <- data.frame(x=c(1,2,10:20))
dd$y <- with(dd,rnorm(13,2+3*x-0.2*x^2,sd=0.4))

In general, if a fitting function in R offers a data argument, it's a good idea to make use of it.

fitResult <- monpol(y~x, degree=3,algorithm="Hawkins",data=dd)

Construct prediction data frame and predict with new data:

pframe <- with(dd,data.frame(x=seq(min(x),max(x),length.out=101)))
pframe$y <- predict(fitResult, newdata=pframe)

Plot results:

par(bty="l",las=1) ## cosmetic
plot(y~x,data=dd,col="red")
lines(dd$x, fitted(fitResult),col="blue",type="b",cex=2)
with(pframe, points(x,y,col="purple",cex=0.5))

enter image description here

Upvotes: 5

Related Questions