2014-09-11 8 views
8

Sono nuovo in ggplot2 e sto cercando di replicare un grafico che ho creato utilizzando filled.contour con ggplot2.filled.contour vs. ggplot2 + stat_contour

sotto è il mio codice:

require(ggplot2) 
require(reshape2) 

#data prep 
scale <- 10 

xs <- scale * c(0, 0.5, 0.8, 0.9, 0.95, 0.99, 1) 
ys <- scale * c(0, 0.01, 0.05, 0.1, 0.2, 0.5, 1) 

df <- data.frame(expand.grid(xs,ys)) 
colnames(df) <- c('x','y') 
df$z <- ((scale-df$x) * df$y)/((scale-df$x) * df$y + 1) 

#filled contour looks good 
filled.contour(xs, ys, acast(df, x~y, value.var='z')) 

#ggplot contour looks bad 
p <- ggplot(df, aes(x=x, y=y, z=z)) 

p + stat_contour(geom='polygon', aes(fill=..level..)) 

io non riesco a capire come ottenere contorno ggplot per riempire i poligoni tutta la strada fino al lato superiore sinistro della mano (c'è un punto in (0,10) con z = 0.99) ... tutto quello che ottiene sono questi triangoli strani

risposta

3

per creare una versione ggplot della trama filled.contour avrete bisogno di avere una grande data.frame rispetto all'oggetto df nel tuo esempio e mediante geom_tile produrrà la trama che stai cercando. Si consideri il seguente:

# a larger data set 
scl <- 10 
dat <- expand.grid(x = scl * seq(0, 1, by = 0.01), 
        y = scl * seq(0, 1, by = 0.01)) 
dat$z <- ((scl - dat$x) * dat$y)/((scl - dat$x) * dat$y + 1) 

# create the plot, the geom_contour may not be needed, but I find it helpful 
ggplot(dat) + 
aes(x = x, y = y, z = z, fill = z) + 
geom_tile() + 
geom_contour(color = "white", alpha = 0.5) + 
scale_fill_gradient(low = "lightblue", high = "magenta") + 
theme_bw()