我正在尝试使用 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"))
谢谢!
最佳答案
这是一个有效的技巧:
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/