如何在成对相关散点图中包含密度着色

How to include density coloring in pairwise correlation scatter plot

我有以下代码:

library(GGally)
library(nycflights13)
library(tidyverse)

dat <- nycflights13::flights %>% 
       select(dep_time, sched_dep_time, dep_delay,  arr_time, sched_arr_time, arr_delay)  %>% 
       sample_frac(0.01)
dat
ggpairs(dat)

它产生这个:

如何添加密度着色使其看起来像这样:

使用来自 How to reproduce smoothScatter's outlier plotting in ggplot? , R - Smoothing color and adding a legend to a scatterplot, and 的想法,您可以定义自己的函数以传递给 ggpairs。

my_fn <- function(data, mapping, ...){
      p <- ggplot(data = data, mapping = mapping) + 
        stat_density2d(aes(fill=..density..), geom="tile", contour = FALSE) +
        scale_fill_gradientn(colours=rainbow(100))
      p
}

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

编辑

来自评论:如何在对角线上添加直方图并在相关值中删除"Corr:"?

您可以设置 diagonal 和 upper 参数。因此,要添加直方图(假设您的意思是 geom_histogram),您可以使用 diag=list(continuous=wrap("barDiag", binwidth=100)) 并完全删除相关性使用 upper=list(continuous="blank")。如果您想实际删除文本 *corr:*,您将需要定义一个新函数 - 请参阅 中的函数 cor_fun

所以你的情节变成了

ggpairs(dat, lower=list(continuous=my_fn),
        diag=list(continuous=wrap("barDiag", binwidth=100)),
        upper=list(continuous=wrap(cor_fun, sz=10, stars=FALSE))
        )

编辑

来自评论:如何像 OP 中那样为对角直方图着色?

要着色,只需将相关参数添加到 barDiag 函数,在本例中为 fillcolour。所以 diag 将是

diag=list(continuous=wrap("barDiag", binwidth=100, fill="brown", col="black")) 

fill 给出主色,col 给出条形轮廓的颜色)