How to fill in the contour fully using stat_contour

后端 未结 2 1542
星月不相逢
星月不相逢 2020-12-15 22:18

I am looking for ways to fully fill in the contour generated by ggplot2\'s stat_contour. The current result is like this:

# Generate data
library(ggplot2)
li         


        
2条回答
  •  情深已故
    2020-12-15 22:45

    Thanks for @chengvt's answer. I sometimes needs this technique, so I made a generalized function().

    test_f <- function(df) {
      colname <- names(df)
      names(df) <- c("x", "y", "z")
      Range <- as.data.frame(sapply(df, range))
      Dim <- as.data.frame(t(sapply(df, function(x) length(unique(x)))))
      arb_z = Range$z[1] - diff(Range$z)/20
      df2 <- rbind(df,
                   expand.grid(x = c(Range$x[1] - diff(Range$x)/20, Range$x[2] + diff(Range$x)/20), 
                               y = seq(Range$y[1], Range$y[2], length = Dim$y), z = arb_z),
                   expand.grid(x = seq(Range$x[1], Range$x[2], length = Dim$x),
                               y = c(Range$y[1] - diff(Range$y)/20, Range$y[2] + diff(Range$y)/20), z = arb_z))
      g <- ggplot(df2, aes(x, y, z = z)) + labs(x = colname[1], y = colname[2], fill = colname[3]) + 
        stat_contour(geom="polygon", aes(fill=..level..)) + 
        coord_cartesian(xlim=c(Range$x), ylim=c(Range$y), expand = F)
      return(g)
    }
    
    library(ggplot2); library(reshape2)
    volcano3d <- melt(volcano)
    names(volcano3d) <- c("xxx", "yyy", "zzz")
    test_f(volcano3d) + scale_fill_gradientn(colours = terrain.colors(10))
    

提交回复
热议问题