Question

I am trying to make a line of best fit in R with the command loess, but the problem is that it should exist of two parts, while my data is only one vector...

so I have this command first:

x = 1:generaties
CI.up = as.numeric(gemiddelde)+as.numeric(ci)
CI.dn = as.numeric(gemiddelde)-as.numeric(ci)
plot(gemiddelde~x, cex=0.5,xaxt='n',ylim=c(0,1.1), xlab='Populatie(a = 100, size = 500, n = 15, tau = 10, c = 50, sigma = 0.5, phenoNumber = 5)',ylab='Fitness', main='Fitness over  generaties',col='blue',pch=16)
axis(1, at=x)
arrows(x,CI.dn,x,CI.up,code=3,length=0.05,angle=90,col='red')

Which gives me a graph

And then I tried adding:

x1 = 1:(generaties/2)
x2 = (generaties/2):generaties
lo1 <- loess(gemiddelde[1:(generaties/2)]~x1)
lo2 <- loess(gemiddelde[(generaties/2):generaties]~x2)
lines(predict(lo1), col='red', lwd=2)
lines(predict(lo2), col='red', lwd=2)

But then I R starts both lines from 0 instead of the second one from half way my graph.

What can I do about this?

Was it helpful?

Solution

You're nearly there I think - just need to specify some x values for the lines() commands. Hopefully the data I've created is representative enough of yours:

#Make up some data
set.seed(0)
generaties <- 20
gemiddelde <- 0.5+0.2*sin(1:generaties)
ci <- runif(generaties)*0.3

#your plot
x = 1:generaties
CI.up = as.numeric(gemiddelde)+as.numeric(ci)
CI.dn = as.numeric(gemiddelde)-as.numeric(ci)
plot(gemiddelde~x, cex=0.5,xaxt='n',ylim=c(0,1.1), xlab='Populatie(a = 100, size = 500, n = 15, tau = 10, c = 50, sigma = 0.5, phenoNumber = 5)',ylab='Fitness', main='Fitness over  generaties',col='blue',pch=16)
axis(1, at=x)
arrows(x,CI.dn,x,CI.up,code=3,length=0.05,angle=90,col='red')

#Adding the loess smoother
x1 = 1:(generaties/2)
x2 = (generaties/2):generaties
lo1 <- loess(gemiddelde[1:(generaties/2)]~x1)
lo2 <- loess(gemiddelde[(generaties/2):generaties]~x2)
lines(x1,predict(lo1), col='red', lwd=2)  #specify x values
lines(x2,predict(lo2), col='red', lwd=2)  #specify x values
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top