Contour Plots for Functions

I am working with the R programming language.

I am trying to make a Contour Plot for the following function:

library(plotly)


  my_function <- function(x,y) {
    
    final_value = x^2 + y^2
    }


input_1 <- seq(-1.5, 1.5,0.1)
input_2 <- seq(-1.5, 1.5,0.1)


z <- outer(input_1, input_2, my_function)

plot_ly(x = input_1, y = input_2, z = z) %>% add_surface()

enter image description here

I am trying to follow the instructions from this link over here: 2D density contour plots in ggplot2 | R CHARTS. In this link, it shows how to make a contour plot for a data frame containing values for two different variables. In my case, it looks like I already have a matrix called "z". I tried to use the code from the website:

# install.packages("ggplot2")
library(ggplot2)

# Data
set.seed(1)

z = data.frame(z)

ggplot(z, aes(x = input_1, y = input_2)) +
  geom_density_2d_filled()

enter image description here

Can someone please tell me if what I have done is correct? Is this how Contour Plots (Level Plots) are made for functions using ggplot2?

The reason I am skeptical is because I tried to repeat this process for a completely different function (Rastrigin function - Wikipedia) and got a very similar result:

 my_function <- function(x1, x2) {
    
    final_value = 20 + x1^2 + x2^2 - 10*(cos(2*pi*x1) + cos(2*pi*x2))
    }


x1 <- seq(-5, 5,0.1)
x2 <- seq(-5, 5,0.1)


z <- data.frame(outer(x1, x2, my_function))


ggplot(z, aes(x = x1, y = x2)) +
  geom_density_2d_filled()

enter image description here

z <- outer(x1, x2, my_function)

plot_ly(x = x1, y = x2, z = z) %>% add_surface()

enter image description here

I don't think this is correct - both functions look entirely different and I doubt they would have the same contour plots. This makes me skeptical and think that I am doing something wrong.

Thanks!

Note: Ideally, the contour plot of the second function should look something like this: https://upload.wikimedia.org/wikipedia/commons/0/0e/Rastrigin-smooth-contour.svg

I would do your first example like this.

library(ggplot2)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
input_1 <- seq(-1.5, 1.5,0.1)
input_2 <- seq(-1.5, 1.5,0.1)
DF <- expand.grid(input_1,input_2)
DF <- DF |> mutate(z=Var1^2+Var2^2)
ggplot(DF, aes(x = Var1, y = Var2,z=z)) +
  geom_contour_filled()

Created on 2022-03-09 by the reprex package (v2.0.1)

1 Like

Thank you so much! I will bookmark this post!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.