Wagner Jorge
Wagner Jorge

Reputation: 430

Changing the color of the contour curve

I'd like to change the color of the contour curve from z variable. My MWE can be seen below.

    library(ggplot2)
    library(tidyverse)

    rosenbrock <- function(x){
        d <- length(x)
        out <- 0
        for(i in 1 : (d - 1)){
            out <- out + 100 * ( x[i]^2 - x[i + 1] )^2 + (x[i] - 1)^2
        }
        out
    }

    set.seed(1)
    coord <- matrix(runif(2000, -50, 50), byrow = TRUE, ncol = 2)
    graph <- apply(coord, 1, rosenbrock)

    results <- data.frame(x = coord[, 1], y = coord[, 2], z = graph) %>%
        arrange(x, y)

    set.seed(2020)
    n <- 5
    x1 <- matrix(c(round(rnorm(n, -12, 5), 2), 0, round(rnorm(n, -6, 5), 2), 0), byrow = F, ncol = 2)
    y1 <- apply(x1, 1, function(x) rosenbrock(x))

    test_points <-  data.frame(x = x1[, 1], y = x1[, 2], 
                       z = y1)    

    results %>% 
        ggplot(aes(x = x, y = y, z = z)) +  
        stat_density2d() +
        geom_point(data = test_points, aes(colour = z), size = 2.0, shape = 19) + 
        scale_colour_gradientn(colours=rainbow(4)) +
        theme_light() +
        labs(colour = 'Fitness')

contour curve

Upvotes: 1

Views: 195

Answers (1)

pgcudahy
pgcudahy

Reputation: 1601

Something like this?

results %>% 
    ggplot(aes(x = x, y = y, z = z)) +  
    stat_density2d(aes(fill = stat(level)), geom = "polygon") +
    geom_point(data = test_points, aes(colour = z), size = 2.0, shape = 19) + 
    scale_colour_gradientn(colours=rainbow(4)) +
    theme_light() +
    labs(colour = 'Fitness')

gradient contour The last few examples at https://ggplot2.tidyverse.org/reference/geom_density_2d.html might be what you're looking for

Upvotes: 1

Related Questions