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

标签 r ggplot2 tidyverse ggally

我有以下代码:

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)

它产生这个:

enter image description here

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

enter image description here

最佳答案

使用来自 How to reproduce smoothScatter's outlier plotting in ggplot? 的想法, R - Smoothing color and adding a legend to a scatterplot , 和 How to use loess method in GGally::ggpairs using wrap function您可以定义自己的函数以传递给 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:”?

您可以设置 diagupper论据。因此,要添加直方图(假设您的意思是 geom_histogram ),您可以使用 diag=list(continuous=wrap("barDiag", binwidth=100))并完全删除相关性使用 upper=list(continuous="blank") .如果你想真正删除文本 *corr:* ,您将需要定义一个新函数 - 请参阅函数 cor_funChange colors in ggpairs now that params is deprecated .

所以你的情节变成
ggpairs(dat, lower=list(continuous=my_fn),
        diag=list(continuous=wrap("barDiag", binwidth=100)),
        upper=list(continuous=wrap(cor_fun, sz=10, stars=FALSE))
        )

enter image description here

编辑

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

要着色,只需将相关参数添加到 barDiag函数,在本例中 fillcolour .所以diag那么将是
diag=list(continuous=wrap("barDiag", binwidth=100, fill="brown", col="black")) 

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

关于r - 如何在成对相关散点图中包含密度着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44961437/

相关文章:

r - 在 R 中安装包 kableExtra 时出错

r - 使音频驱动程序在R中可用?

r - 内插空间数据

r - 垂直点显示同一图中多个组的分布

r - 使用 ggplot 中 after_stat 的数据来控制堆叠条的标签位置

r - 构建函数以将自然中断 jenks 应用于我的 df 列时出错

R - 在保持记录顺序的同时删除重复列表

r - 修改 `citation`中的 `R`对象

r - 在堆积区域图中将悬停文本格式化为 $ (R/Plot.ly)

r - 如何在独立层的ggplot中缩放颜色?