ggpairs:用因子

时间:2017-08-14 18:51:10

标签: r colors correlation scatter-plot

我试图用ggpairs复制可以成对轻松完成的任务 - 即用二元因子(代表一个类)对geoms(例如散点等)进行着色。但是我不能。以下是使用ISLR库中的数据集Smarket的可重现示例:

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

返回以下图表:

enter image description here

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

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

enter image description here

但我试图通过Class为geoms着色失败:

> 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 arguements

您的建议将不胜感激。

@ 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的最新二进制文件重新安装它。然后它奏效了。

1 个答案:

答案 0 :(得分:0)

您可以使用ggplot添加标准ggpairs美学,因此将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))

enter image description here