在R和ggpairs中定义用户自定义的颜色调色板

7

我正在尝试为R中GGally库中的ggpairs散点图使用另一个颜色调色板。请参见此处类似问题

library(ggplot2)
library(GGally)

工作

ggplot(iris, aes(x=Sepal.Width, colour=Species)) + stat_ecdf() + scale_color_brewer(palette="Spectral")

ggplot2_1

同样适用

ggplot <- function(...) ggplot2::ggplot(...) + scale_color_brewer(palette="Spectral")
ggplot(iris, aes(x=Sepal.Width, colour=Species)) + stat_ecdf()

ggplot2_2

Does not work

ggplot <- function(...) ggplot2::ggplot(...) + scale_color_brewer(palette="Spectral")

ggpairs(iris, 
    columns=, c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width"),
    colour='Species',
    lower=list(continuous='points'), 
    axisLabels='none',  
    upper=list(continuous='blank')
)

ggpairs1但是添加

putPlot(p, ggplot(iris, aes(x=Sepal.Length, colour=Species)) + stat_ecdf(), 1,1)

添加正确颜色的绘图。

ggpairs2

解决方法

我可以使用getPlot后更改绘图,但那不够美观...

subplot <- getPlot(a, 2, 1) # retrieve the top left chart
subplotNew <- subplot + scale_color_brewer(palette="Spectral")
a <- putPlot(a, subplotNew, 2, 1)

我该如何更改ggpairs中散点图的颜色方案?更具体地说,我想手动定义颜色,如下所示:

scale_colour_manual(values=c("#FF0000","#000000", "#0000FF","#00FF00"))

谢谢!


你可以将ggpairs图存储在一个对象中,比如说gg,然后修改gg$plots - Stéphane Laurent
2个回答

3

以下是可行的黑客方法:

ggplot <- function(...) ggplot2::ggplot(...) + scale_color_brewer(palette="Spectral")
unlockBinding("ggplot",parent.env(asNamespace("GGally")))
assign("ggplot",ggplot,parent.env(asNamespace("GGally")))

当你为ggplot函数分配一个新值时,它将在全局环境中。现在,GGally在加载时会导入一切,包括ggplot(本来不必如此)。此时,更改全局环境中的ggplot函数不起作用,因为来自GGally的导入具有优先权。相反,您需要更新GGally:imports上的ggplot函数。只有一个问题:一旦加载了包,其绑定就会被锁定。但是我们可以解锁它们(我想这是不受欢迎的,因此将其标记为hack解决方案)。
请参见Josh O'Brien在Replace definition of built-in function in R?下的回答以获取更多信息。

0

正如stacksia所说(但也要添加scale_fill_brewer)

ggplot <- function(...) ggplot2::ggplot(...) + scale_color_brewer(palette="Spectral") + scale_fill_brewer(palette="Spectral")
unlockBinding("ggplot",parent.env(asNamespace("GGally")))
assign("ggplot",ggplot,parent.env(asNamespace("GGally")))

请参考Josh O'Brien在Replace definition of built-in function in R?下的回答获取更多信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接