5

使用以下代码:

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

我可以创建这个情节:

在此处输入图像描述

我的问题是如何使用以下方案更改 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()

哪个产生这个:在此处输入图像描述

4

1 回答 1

6

使用类似于Change colours 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 <- eval_data_col(data, mapping$x)
      Y <- eval_data_col(data, 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()

产生:

在此处输入图像描述

于 2017-07-08T13:11:26.370 回答