我在cnicollet的帮助下开发了代码 - 请参阅下面的评论 - 从GGally包中定制ggpairs - 见下文 - 并按年份分配颜色(以便年份之间的差异变得明显):
library(ISLR)
library(data.table)
library(GGally)
library(ggplot2)
data(Auto, package = "ISLR")
Auto2 <- Auto[, c(1:3, 7:8)]
Auto2$year = ifelse(Auto2$year < 76, 0, 1)
Auto2$cylinders <- factor(Auto2$cylinders)
Auto2$origin <- factor(Auto2$origin)
Auto2$year <- factor(Auto2$year)
ggpairs(Auto2 , ggplot2::aes(colour=year),
lower = list(continuous = wrap("points", color = "red", alpha = 0.5),
combo = wrap("box", color = "orange", alpha = 0.3),
discrete = wrap("facetbar", color = "yellow", alpha = 0.3) ),
diag = list(continuous = wrap("densityDiag", color = "blue", alpha = 0.5) ))
现在我想将调用嵌入到一个函数中,该函数将包含表示该类的变量的数据和名称作为参数,并将该图作为对象返回而不显示它。
首先尝试:
pairplots = function(data, class){
library(GGally)
library(ggplot2)
p = ggpairs(data , ggplot2::aes(colour= class),
lower = list(continuous = wrap("points", color = "red", alpha = 0.5),
combo = wrap("box", color = "orange", alpha = 0.3),
discrete = wrap("facetbar", color = "yellow", alpha = 0.3) ),
diag = list(continuous = wrap("densityDiag", color = "blue", alpha = 0.5) ))
p
}
pairplots(data = Auto2, class = 'year')
第二次尝试:
pairplots = function(data, class){
library(GGally)
library(ggplot2)
p = ggpairs(data , ggplot2::aes(colour= data[, class]),
lower = list(continuous = wrap("points", color = "red", alpha = 0.5),
combo = wrap("box", color = "orange", alpha = 0.3),
discrete = wrap("facetbar", color = "yellow", alpha = 0.3) ),
diag = list(continuous = wrap("densityDiag", color = "blue", alpha = 0.5) ))
p
}
pairplots(data = Auto2, class = 'year')
两次尝试都会导致异常。
您的建议将不胜感激。