# define function
fun <- function(x){
exp(-rowSums(x^2)/2)
}
# define xgrid
nx <- 101
x <- y <- seq(-3, 3, length.out = nx)
xy <- expand.grid(x1 = x, x2 = y)
# evaluate function
z <- matrix(fun(xy), nx, nx)
# define colors
colors <- c("#053061", "#2166ac", "#4393c3", "#92c5de", "#d1e5f0", "#f7f7f7",
"#fddbc7", "#f4a582", "#d6604d", "#b2182b", "#67001f")
col <- colorRampPalette(colors)(21)
# setup par
oplt <- par()$plt
par(plt = c(0.15, 0.8, oplt[3:4]))
# plot image
image(x, y, z, col = col)
# add legend
par(plt = c(0.85, 0.9, oplt[3:4]), new = TRUE)
color.legend(range(z), col = col, ncol = length(col))
# restore original par()$plt
par(plt = oplt)
Run the code above in your browser using DataLab