-->

有没有办法来改变使用ggplot GGally :: ggpairs调色板?(is there a

2019-07-19 07:15发布

我想改变颜色的调色板为GGally功能ggpairs 。 当我尝试ggplot命令添加到ggplot使用退换getPlot ,颜色不会改变。

my_pair_plot = ggpairs(dataset, color="var1")
getPlot(my_pair_plot,2,1) + scale_fill_brewer(palette = "Set2")

试图把ggplot的命令直接ggpairs在误差函数的结果。

ggpairs(dataset, color="var1") + scale_fill_brewer(palette = "Set2")

Answer 1:

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

ggpairs

让我们看看我们是否能够找到任何AES映射填充或颜色。 确实,

combo_aes <- addAndOverwriteAes(aes_string(x = xColName, 
            y = yColName, ...), section_aes)

我们可能希望它做什么,它说。 两个重要的注意事项:

  • 颜色和填充AES应包含在省略号的ggpairs通话

  • aes_string()是用来

让我们尝试了这一点:

ggpairs(diamonds[, 1:2], colour='cut')

太好了,我们快到了! 我们只需要覆盖调色板。 需要注意的是像你建议

ggpairs(diamonds[, 1:2], colour='cut') + scale_fill_brewer(palette = "Set2")

不会起作用,因为ggpairs对象不是ggplot,所以+符号是不能直接适用于任何方式。 然而,简单的解决方法提供了这里 。 用你的手指,并...

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



Answer 2:

update:

GGAlly was updated again and the hack in this answer also doesn’t work anymore, but finally there’s a non-hack solution: given

scales <- scale_colour_brewer(type = 'qual') %+% scale_fill_brewer(type = 'qual')

you can do (in a hopefully future-proof way)

for (row in seq_len(ps$nrow))
    for (col in seq_len(ps$ncol))
        ps[row, col] <- ps[row, col] + scales

old way

The hack in the other answer does not work anymore, so let’s hack a new one!

The internal structure of a ggpairs object is the dataset and a list of strings:

> 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

In order to modify the plot, the respective strings in the plot object need to be modified to include the additional command. For this, we use deparse(substitute(argument)) to get a string containing the code the user passed, and append it to every plot call:

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'))



文章来源: is there a way to change the color palette for GGally::ggpairs using ggplot?