有没有办法使用ggplot更改GGally :: ggpairs的调色板?

Gle*_*ker 17 r palette ggplot2

我想更改GGally功能的调色板ggpairs.当我尝试将ggplot命令添加到使用返回的ggplot时getPlot,颜色不会改变.

my_pair_plot = ggpairs(dataset, color="var1")
getPlot(my_pair_plot,2,1) + scale_fill_brewer(palette = "Set2")
Run Code Online (Sandbox Code Playgroud)

尝试将ggplot命令直接放在ggpairs函数上会导致错误.

ggpairs(dataset, color="var1") + scale_fill_brewer(palette = "Set2")
Run Code Online (Sandbox Code Playgroud)

ton*_*nov 6

事实证明,这是可能的!它需要查找源代码,但解决方案很容易实现.我们对ggpairs功能感兴趣,所以第一步就是

ggpairs
Run Code Online (Sandbox Code Playgroud)

让我们看看我们是否可以找到任何aes映射来填充或着色.确实,

combo_aes <- addAndOverwriteAes(aes_string(x = xColName, 
            y = yColName, ...), section_aes)
Run Code Online (Sandbox Code Playgroud)

我们可能希望它能够实现它所说的.两个重要说明:

  • 颜色和填充aes应包含在ggpairs调用的省略号中

  • aes_string() 用来

我们来试试吧:

ggpairs(diamonds[, 1:2], colour='cut')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

很好,我们快到了!我们只需要覆盖调色板.请注意,像你提出的建议

ggpairs(diamonds[, 1:2], colour='cut') + scale_fill_brewer(palette = "Set2")
Run Code Online (Sandbox Code Playgroud)

因为ggpairs对象不是ggplot所以不起作用,因此+符号不能以任何方式直接应用.但是,这里提供了简单的解决方法.交叉你的手指,......

ggplot <- function(...) ggplot2::ggplot(...) + scale_fill_brewer(palette="Set2")
ggpairs(diamonds[, 1:2], colour='cut')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


fly*_*eep 6

更新:

GGAlly再次更新,这个答案的黑客攻击不再适用,但最后有一个非黑客的解决方案:给出

scales <- scale_colour_brewer(type = 'qual') %+% scale_fill_brewer(type = 'qual')
Run Code Online (Sandbox Code Playgroud)

你能做到(希望以未来的方式)

for (row in seq_len(ps$nrow))
    for (col in seq_len(ps$ncol))
        ps[row, col] <- ps[row, col] + scales
Run Code Online (Sandbox Code Playgroud)

老路

另一个答案中的黑客不再起作用,所以让我们破解一个新的!

ggpairs对象的内部结构是数据集和字符串列表:

> dta <- data.frame(a=1:6, b=7:12, c=c('f', 'g'))
> ps <- ggpairs(dta, 1:2, colour = 'c')
> str(ps)
List of 10
 $ data        :'data.frame':   2 obs. of  3 variables:
  ..$ a: int [1:2] 1 2
  ..$ b: int [1:2] 3 4
  ..$ c: int [1:2] 5 6
 $ columns     : int [1:3] 1 2 3
 $ plots       :List of 9
  ..$ : chr "ggally_densityDiag(ggally_data, ggplot2::aes(x = a, colour = c))"
  ..$ : chr "ggally_cor(ggally_data, ggplot2::aes(x = b, y = a, colour = c))"

[...]

 $ gg          : NULL
 - attr(*, "class")= chr [1:2] "gg" "ggpairs"

> ps
Run Code Online (Sandbox Code Playgroud)

情节之前

为了修改绘图,需要修改绘图对象中的相应字符串以包含附加命令.为此,我们使用deparse(substitute(argument))获取包含用户传递的代码的字符串,并将其附加到每个绘图调用:

add_to_plots <- function(pairs, modification) {
    str <- deparse(substitute(modification))
    pairs$plots <- lapply(pairs$plots, function(s) paste(s, '+', str))
    pairs
}

> add_to_plots(ps, scale_colour_brewer(type = 'qual'))
Run Code Online (Sandbox Code Playgroud)

情节之后