【问题标题】:User defined colour palette in R and ggpairsR 和 ggpairs 中用户定义的调色板
【发布时间】:2014-03-06 21:38:28
【问题描述】:

我正在尝试为 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")

也有效

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

不起作用

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

但添加

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

以正确的颜色添加绘图。

解决方法

之后我可以使用 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

标签: r ggplot2


【解决方案1】:

这是一个有效的技巧:

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? 下的回答。

【讨论】:

    【解决方案2】:

    正如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? 下的回答。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-08
      • 1970-01-01
      • 1970-01-01
      • 2014-11-03
      • 2021-01-19
      • 2020-10-09
      • 1970-01-01
      • 2014-11-15
      相关资源
      最近更新 更多