如何在GGally中使用自己的密度函数创建低密度图

时间:2017-07-08 09:51:19

标签: r ggplot2 ggally

使用以下代码:

library(GGally)
library(tidyverse)
library(viridis)


dat <- iris %>% select(-Species)

my_fn <- function(data, mapping, ...){
      # Using default ggplot density function

      p <- ggplot(data = data, mapping = mapping) + 
        stat_density2d(aes(fill=..density..), geom="tile", contour = FALSE) +
        scale_fill_gradientn(colours=viridis::viridis(100, option="viridis"))
      p
}


ggpairs(dat, lower=list(continuous=my_fn)) +
  theme_void()

我可以创建这个情节:

enter image description here

我的问题是如何使用以下方案更改GGally低密度图:

library(MASS)
# Get density of points in 2 dimensions.
# @param x A numeric vector.
# @param y A numeric vector.
# @param n Create a square n by n grid to compute density.
# @return The density within each square.
get_density <- function(x, y, n = 100) {
  dens <- MASS::kde2d(x = x, y = y, n = n)
  ix <- findInterval(x, dens$x)
  iy <- findInterval(y, dens$y)
  ii <- cbind(ix, iy)
  return(dens$z[ii])
}



# Data wrangling method2 --------------------------------------------------
theme_set(theme_bw(base_size = 16))
tbl <- as.tibble(iris) %>% 
        select(-Species)


# tbl
dens_wrapper <- function (tbl=NULL, var1=NULL, var2=NULL) {
  tbl_pair <- tbl %>%
                select_(var1, var2)
  x <- tbl_pair %>% pull(var1)
  y <- tbl_pair %>% pull(var2)
  tbl_pair$density <- get_density(x,y)
  tbl_pair
}

feature1 = "Sepal.Length"
feature2 = "Petal.Length"
tbl_pair1 <- dens_wrapper(tbl=tbl, var1=feature1, var2=feature2) 
ggplot(tbl_pair1) +
  geom_point(aes_string(feature1, feature2, color = 'density')) +
  scale_color_viridis()

哪个产生了这个:enter image description here

1 个答案:

答案 0 :(得分:4)

使用与Change colors in ggpairs now that params is deprecated类似的想法,您只需将计算添加到您自己定义的函数中。

my_fn <- function(data, mapping, N=100, ...){

      get_density <- function(x, y, n ) {
                  dens <- MASS::kde2d(x = x, y = y, n = n)
                  ix <- findInterval(x, dens$x)
                  iy <- findInterval(y, dens$y)
                  ii <- cbind(ix, iy)
                  return(dens$z[ii])
                }

      X <- data[,as.character(mapping$x)]
      Y <- data[,as.character(mapping$y)]

      data$density <- get_density(x=X, y=Y, n=N)

      p <- ggplot(data, mapping) +
               geom_point(aes(colour=density), ...) +
               scale_color_viridis()      
      p
}

 ggpairs(dat, lower=list(continuous=my_fn)) +
 theme_bw()

产地:

enter image description here