简体   繁体   中英

incorrect values of x, y axis using contour plot

I wanted to create a contour plot using the ggplot library. I checked the documentation on this topic, and found the code to get this done. Unfortunately the code uses the indexes of the matrix z storing the surface, as x and y. How do I change this to the actual value of x and y? Below my code generating the contour plot.

objective_function <- function(vec) {
  basin_function <- function(vec){
    if(all(vec == 0)) {
      return(0)
    } else{
      return(sum(exp(-2.0/vec^2)+sin(vec*pi*2)))
    }
  }
  return(basin_function(vec))
}

objective_function_wrapper <- function(x_vec, y_vec) {
  vec <-rbind(x_vec,y_vec)
  return(apply(vec,2, objective_function))
}

plotSurf <-function(){
    x <- y <-seq(from=-5, to =5,  by=0.1)
    z <- outer(x,y, objective_function_wrapper)
    surf3d <- melt(z)
    names(surf3d) <- c("x", "y", "z")
    p1 <- ggplot(data=surf3d, aes(x=x, y=y, z=z))
    p1 <- p1 + geom_tile(aes(fill=z))+stat_contour()
    print(p1)
}

plotSurf()

You need to substitute the x - and y -values for the row and column numbers that are currently sitting in the "melt"-ed result of the outer call:

x <- y <-seq(from=-5, to =5,  by=0.1)
z <- outer(x,y, objective_function_wrapper)
surf3d <- melt(z)
names(surf3d) <- c("x", "y", "z")
surf3d$x <- rep(x, ncol(z) ); surf3d$y <- rep(y, each=nrow(z) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM