r - R 和 ggpairs 中用户定义的调色板

标签 r ggplot2

我正在尝试使用 R 中 GGally 库中 ggpairs 的另一个调色板来绘制散点图。请参阅 similar question here .

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

不起作用

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

谢谢!

最佳答案

这是一个有效的技巧:

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 函数。只有一个问题:一旦加载了一个包,它的绑定(bind)就会被锁定。但我们可以解锁它们(我猜这是不受欢迎的,因此将解决方案标记为黑客)。

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

关于r - R 和 ggpairs 中用户定义的调色板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22237783/

相关文章:

r - 在小插图中为包本身加载 R 包

r - Knitr:将代码块中的文本打印为R markdown

r - ggplot2 更改每个单独方面面板的轴限制

r - 当枢轴 = TRUE 时,R 中的 Cholesky 分解可得到逆矩阵

r - dplyr 的过滤函数 : how to return every value (or «cancel» the effect of filter)?

r - 在 R 中使用 ggplot2 绘制地铁图

r - 尝试在 ggplot 中的直方图上应用颜色渐变

r - 在 ggplot 中的每个方面手动排序 x 轴标签

r - 在geom_boxplot中更改晶须定义

重新排序闪避条形图 (ggplot2)