2014-09-11 63 views
8

我是ggplot2的新手,我試圖複製一張使用ggplot2使用filled.contour創建的圖形。filled.contour與ggplot2 + stat_contour

下面

是我的代碼:

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

我無法弄清楚如何讓ggplot輪廓,以填補多邊形一路攀升到左上方(有在一個點(0,10 )與Z = 0.99)......我得到的是這些怪異的三角形

回答

3

要創建ggplot版本filled.contour情節的,你需要有一個比你的榜樣的df對象大data.frame和使用geom_tile會產生你正在尋找的情節。考慮以下幾點:

# 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()