TheChainsOfMarkov
TheChainsOfMarkov

Reputation: 323

stat_countour() cannot generate contour lines (ggplot2)

folks:

I can't seem to generate a contour plot using ggplot2's stat_countour() command. Here's an example of what I'm trying to do:

df <- data.frame(matrix(NA, nrow = 100, ncol = 3))
names(df) <- c("X","Y","Z")
df$X <- seq(0,1, by=1/99)
df$Y <- seq(0,1, by=1/99)
df$Z <- exp(0.8*log(df$X) + 0.2*log(df$Y))

v <- ggplot(df, aes(x=C, y=Y, z = Z))
v + stat_contour()

I get the dreaded Not possible to generate contour data error. Everything I've looked at seems to imply that this error comes when the matrix isn't regular--but, by definition my X and Y seem to be regular.

I've tried stat_density() with no success either. Any help would be appreciated!

Upvotes: 0

Views: 643

Answers (1)

josliber
josliber

Reputation: 44330

In your posted code you haven't defined a grid but instead of data frame where X equals Y. You can create a grid with the expand.grid function and then define Z to be some function of X and Y:

library(ggplot2)
dat <- expand.grid(X=seq(0,1, by=1/99), Y=seq(0,1,by=1/99))
dat$Z <- exp(0.8*log(dat$X) + 0.2*log(dat$Y))
ggplot(dat, aes(x=X, y=Y, z=Z))+stat_contour()

enter image description here

Upvotes: 4

Related Questions