stat_contour not able to generate contour lines

Florian R. Klein picture Florian R. Klein · Sep 28, 2013 · Viewed 12.7k times · Source

I need to add lines via stat_contour() to my ggplot/ggplot2-plot. Unfortunately, I can not give you the real data from which point values should be evaluated. However, another easily repreducably example behaves the same:

testPts <- data.frame(x=rep(seq(7.08, 7.14, by=0.005), 200))
testPts$y <- runif(length(testPts$x), 50.93, 50.96)
testPts$z <- sin(testPts$y * 500)

ggplot(data=testPts, aes(x=x, y=y, z=z)) + geom_point(aes(colour=z))
       + stat_contour()

This results in the following error message:

Error in if (nrow(layer_data) == 0) return() : argument is of length zero In addition: Warning message: Not possible to generate contour data

The example looks not different from others posted on stackoverflow or in the official manual/tutorial to me, and it seemingly doesn't matter if I provide more specifications to stat_contour. It seems the function does not pass the data(-layer) as pointed ou tint the error message.

Answer

Andy W picture Andy W · Sep 29, 2013

Use stat_density2d instead of stat_contour with irregularly spaced data.

library(ggplot2)

testPts <- data.frame(x=rep(seq(7.08, 7.14, by=0.005), 200))
testPts$y <- runif(length(testPts$x), 50.93, 50.96)
testPts$z <- sin(testPts$y * 500)

(ggplot(data=testPts, aes(x=x, y=y, z=z))
+ geom_point(aes(colour=z))
+ stat_density2d()
)

enter image description here