Reputation: 175
I need to draw a contour plot of a certain function, plot a few points on it, and connect those points. I have done all of those things except the last one: I don't know how to use the lines()
function to connect the points.
Here's the code that will generate the points (it's a minimization procedure, the points are contained in the table called "tabela")
n=2; x=c(1,4) # número de tentativa, ponto inicial
f = function(x,y){((x)-3)^2+(3*x-2*y)^4} # função objetivo
fexpr=expression(((x+lambda*e1)-3)^2+(3*(x+lambda*e1)-2*(y+lambda*e2))^4) # transforma em expressão
deriv_1=function(x,y,e1,e2,lambda){eval(D(fexpr,'lambda'))} # derivada
deriv_2=function(x,y,e1,e2,lambda){eval(D(D(fexpr,'lambda'),'lambda'))}
tabela=data.frame() # inicia uma tabela a ser preenchida pelo for loop
i=1
for (k in 0:100){
e=diag(1,nrow = n)[,i]
lambda=0
for (j in 1:10){
lambda=lambda-deriv_1(x=x[1],y=x[2],e1=e[1],e2=e[2],lambda=lambda)/
deriv_2(x=x[1],y=x[2],e1=e[1],e2=e[2],lambda=lambda)
}
f_x=eval(fexpr,list(x=x[1],y=x[2],e1=0,e2=0,lambda=0))
linha_tabela=data.frame(k=k,x=x[1],y=x[2],f_x=f_x,lambda=lambda)
tabela=rbind(tabela,linha_tabela)
x=x+lambda*e
if (i<n){i=i+1}else{i=1}
}
Then the contour is generated by
funcao = function(x,y){((x)-3)^2+(3*x-2*y)^4} # função objetivo
x1 = seq(0,5,length=100)
x2 = seq(0,5,length=100)
all.x = expand.grid(x1,x2)
eval.fx = funcao(x=all.x$Var1, y=all.x$Var2)
fx = matrix(data = eval.fx, nrow=length(x1), ncol=length(x2), byrow=FALSE)
# persp(x=x1, y=x2, z=fx, col="red", xlim=c(-15,15), ylim=c(-15,15), scale=TRUE, shade=0.4)
par(pty="m")
contour(x=x1, y=x2, z=fx, col='navy', lwd=2,
main= expression(paste("Gráfico de Contorno para a função ", f(x,y))),
xlab = expression(x[1]),
ylab= expression(x[2]),
xlim=c(0,5),
ylim=c(0,5), levels = seq(1,100,length=10))
# gerando uma grade no plot
abline(h = seq(from = -10, to = 30, by = 5), lty = "dotted", col = "lightgray")
abline(v = seq(from = -10, to = 30, by = 5), lty = "dotted", col = "lightgray")
# marcando os eixos x e y
abline(h = 0, lwd = 2)
abline(v = 0, lwd = 2)
# exibe os pontos convergindo
points(tabela[1:7,2:3], col='red', pch=19)
Here's what it looks like. I need lines connecting the points! Thanks for any help.
Upvotes: 1
Views: 121
Reputation: 3335
Is this response surface methodology? You can connect the dots with lines by the code lines(tabela[1:7, 2:3], col="black")
after creating the plot with the points.
Upvotes: 1