The documentation for geom_contour
and geom_contour_filled
is quite misleading: it suggests that things work best when x
and y
form a grid, but in fact, things don't work at all unless they form a grid.
To make a grid from random (x,y,z)
triplets, you can use the akima::interp
function. For example, starting with your data:
library(tidyverse)
# x and y are generated from uniform random distribution
x <- runif(1000, min = -5, max = 5)
y <- runif(1000, min = -5, max = 5)
z <- x^2 + y^2
tbl <- tibble(x, y, z)
grid <- akima::interp(tbl$x, tbl$y, tbl$z)
griddf <- data.frame(x = rep(grid$x, ncol(grid$z)),
y = rep(grid$y, each = nrow(grid$z)),
z = as.numeric(grid$z))
ggplot(data = griddf,
aes(x = x,
y = y,
z = z)) +
geom_contour_filled(alpha = 0.8) +
scale_fill_viridis_d(drop = FALSE)
Be careful: akima
is not part of the tidyverse
, so you need to convert the result to a tibble/dataframe by hand, and it's easy to get that wrong. I think I got it right, but since your function is symmetric, I'm not 100% sure.
Just noticed another solution for the reshaping here: https://stackoverflow.com/a/22895190/2554330. You might like that one better than mine (or not, it's a matter of taste).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…