【问题标题】:How to include density coloring in pairwise correlation scatter plot如何在成对相关散点图中包含密度着色
【发布时间】:2017-12-11 04:48:57
【问题描述】:

我有以下代码:

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)

它产生这个:

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

【问题讨论】:

  • 使用 ggpairs(dat, lower = list(continuous = "density")) 怎么样?
  • @ed_sans 不是我想要的。需要像 OP 中的相关性这样的散点图。

标签: r ggplot2 tidyverse ggally


【解决方案1】:

使用来自 How to reproduce smoothScatter's outlier plotting in ggplot?R - Smoothing color and adding a legend to a scatterplotHow 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:”?

您可以设置diagonal 和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 函数,在本例中为fillcolour。所以diag 会是

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

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

【讨论】:

  • 非常感谢。如何在对角线上添加直方图并去除相关值中的“Corr:”?
  • 您介意将结果图添加到您的答案中吗?
  • @user20650 很好的答案。你如何像在 OP 中那样为对角线直方图着色?
  • @user20650 你介意看看这个stackoverflow.com/questions/44984822/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-11
  • 2018-01-07
  • 2013-12-05
  • 1970-01-01
  • 2021-06-16
  • 1970-01-01
相关资源
最近更新 更多