Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
614 views
in Technique[技术] by (71.8m points)

r - empty contour plot in ggplot

I am trying to create a simple contour plot.

Sample code is attached below. The output is an empty plot with labels and with warning messages -

1: stat_contour(): Zero contours were generated 
2: In min(x) : no non-missing arguments to min; returning Inf
3: In max(x) : no non-missing arguments to max; returning -Inf

Can someone please help me fix it.

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)

ggplot(data = tbl,
       aes(x = x,
           y = y,
           z = z)) + 
  geom_contour_filled(alpha = 0.8) + 
  scale_fill_viridis_d(drop = FALSE) + 
question from:https://stackoverflow.com/questions/65873211/empty-contour-plot-in-ggplot

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

enter image description here

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...