我有以下代码:
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 , 和 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:”?
您可以设置
diag
和 upper
论据。因此,要添加直方图(假设您的意思是 geom_histogram
),您可以使用 diag=list(continuous=wrap("barDiag", binwidth=100))
并完全删除相关性使用 upper=list(continuous="blank")
.如果你想真正删除文本 *corr:*
,您将需要定义一个新函数 - 请参阅函数 cor_fun
在 Change 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))
)
编辑
来自评论:您如何像在 OP 中那样为对角线直方图着色?
要着色,只需将相关参数添加到
barDiag
函数,在本例中 fill
和 colour
.所以diag
那么将是diag=list(continuous=wrap("barDiag", binwidth=100, fill="brown", col="black"))
(
fill
给出了主色,col
给出了条形轮廓的颜色)
关于r - 如何在成对相关散点图中包含密度着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44961437/