ggpairs :按一个因素给几何着色

ggpairs : Colouring the geoms by a Factor

我正在尝试使用 ggpairs 复制可以轻松成对完成的操作——即通过二进制因子(代表 Class)为几何图形(例如散点等)着色。但是我不能。下面是一个使用 ISLR 库中的数据集 Smarket 的可重现示例:

library(ISLR)
data(Smarket)
pairs(Smarket, col = Smarket$Direction)

这个returns下图:

现在,使用 ggpairs 而不通过 Class 指定颜色,我得到以下图:

Smarket$Class <- ifelse(Smarket$Direction == "Up", 1, -1)

ggpairs(Smarket %>% select(-9) , 
        lower = list(continuous = wrap("points", color = "red", alpha = 0.5), 
                     combo = wrap("box", color = "blue", alpha = 0.3), 
                     discrete = wrap("facetbar", color = "orange", alpha = 0.3) ), 
        diag = list(continuous = wrap("densityDiag",  color = "yellow", alpha = 0.5) ))

但是我尝试通过 Class 给几何着色的尝试失败了:

> color_by_Class <- as.factor(ifelse(Smarket$Direction == "Up", "red", "black"))
> ggpairs(Smarket %>% select(-9) , 
+         lower = list(continuous = wrap("points", color = color_by_Class, alpha = 0.5), 
+                      combo = wrap("box", color = "orange", alpha = 0.3), 
+                      discrete = wrap("facetbar", color = color_by_Class, alpha = 0.3) ), 
+         diag = list(continuous = wrap("densityDiag",  color = color_by_Class, alpha = 0.5) ))
Error: Aesthetics must be either length 1 or the same as the data (512): colour, alpha
> length(color_by_Class)
[1] 1250
> dim(Smarket %>% select(-9))
[1] 1250    8

> ggpairs(Smarket %>% select(-9) , 
+         lower = list(continuous = wrap("points", aes(color = color_by_Class), alpha = 0.5), 
+                      combo = wrap("box", aes(color = color_by_Class), alpha = 0.3), 
+                      discrete = wrap("facetbar", aes(color = color_by_Class), alpha = 0.3) ), 
+         diag = list(continuous = wrap("densityDiag",  aes(color = color_by_Class), alpha = 0.5) ))
Error in wrap("points", aes(color = color_by_Class), alpha = 0.5) : 
  all parameters must be named arguments

我们将不胜感激您的建议。

@jdb

感谢您优雅的解决方案。但是,当我复制并粘贴您的代码并 运行 时,出现错误(见下文)。你能帮我理解为什么吗?

> library(dplyr)
> library(ggplot2)
> library(ISLR)
> library(GGally)
> data(Smarket)
> 
> Smarket$Class <- ifelse(Smarket$Direction == "Up", 1, -1)
> Smarket$Class <- as.factor(Smarket$Class)
> 
> ggpairs(Smarket %>% select(-9), aes(colour = Class, alpha = 0.4))
Error in FUN(X[[i]], ...) : 
  only defined on a data frame with all numeric variables
In addition: Warning message:
`panel.margin` is deprecated. Please use `panel.spacing` property instead 

@jdb

再次感谢您。我删除了 GGally 并使用来自 CRAN 的最新二进制文件重新安装了它。然后就成功了。

您可以使用 ggpairs 添加标准 ggplot 美学,因此将 Class 变量转换为一个因子并使用 colour 美学应该可以解决问题。

library(dplyr)
library(ggplot2)
library(ISLR)
library(GGally)
data(Smarket)

Smarket$Class <- ifelse(Smarket$Direction == "Up", 1, -1)
Smarket$Class <- as.factor(Smarket$Class)

ggpairs(Smarket %>% select(-9), aes(colour = Class, alpha = 0.4))