2012-04-20 3 views
2

가능한 모든 변수 조합에 대한 그래프를 그립니다. 내 코드는 다음과 같습니다.ggplot2 : 가능한 모든 변수 조합에 대한 산점도

set.seed(12345) 
a <- data.frame(Glabel=LETTERS[1:7], A=rnorm(7, mean = 0, sd = 1), B=rnorm(7, mean = 0, sd = 1), C=rnorm(7, mean = 0, sd = 1)) 
T <- data.frame(Tlabel=LETTERS[11:20], A=rnorm(10, mean = 0, sd = 1), B=rnorm(10, mean = 0, sd = 1), C=rnorm(10, mean = 0, sd = 1)) 

library(ggplot2) 
for(i in 2:(ncol(a)-1)) 
{ 
for(j in (i+1):ncol(a)) 
{ 
    r <- 0.08 
    p <- ggplot(data=a, mapping=aes(x=a[, i], y=a[, j])) + geom_point() + theme_bw() 
    p <- p + geom_text(data=a, mapping=aes(x=a[, i], y=a[, j], label=Glabel), 
       size=3, vjust=1.35, colour="black") 
    p <- p + geom_segment(data = T, aes(xend = T[ ,i], yend=T[ ,j]), 
        x=0, y=0, colour="black", 
        arrow=arrow(angle=25, length=unit(0.25, "cm"))) 
    p <- p + geom_text(data=T, aes(x=T[ ,i], y=T[ ,j], label=Tlabel), size=3, vjust=0, colour="red") 
dev.new() 
    print(p) 
} 
} 

이 코드는 정상적으로 작동합니다. 그러나 여기에 사용 된 방법은 권장되지 않으며 (See @baptiste comment) 기능 상 작동하지 않습니다. 이 작업을 수행하기 위해 최선의 방법과 권장 방법이 무엇인지 알고 싶습니다. 귀하의 도움에 미리 감사드립니다.

+2

당신이 GGally 패키지에서 ggpairs 봤어 :이 조금 더 낫다? – joran

+0

@ 조란 그것은 좋은 생각이지만이 질문 자체는 꽤 흥미 롭습니다. 나는 쉽게 접근 할 수 있지만 ggplot은 데이터 세트의 객체를 제공해야하며, lapply 할 때마다 함수 호출 안에서 비효율적으로 가짜 데이터 세트를 만들 수는 없다. –

+1

아마 아래의 내 답변을 사용하여 추가 한 항목을 넣을 수 있습니다. 스레드에서 편집자가 편집자가 "원본"질문과 같이 보이지 않는 이유를 이해하지 못한다고 말하지 않으면 내용을 변경하지 마십시오. . –

답변

3

좋아, 이건 쓰레기지만 내가 할 수있는 최선이야. lapply을 통해 각 루프의 부분 데이터를 재생성하므로 비효율적입니다.

MAT <- outer(names(df)[-1], names(df)[-1], paste) 
combs <- sapply(MAT[lower.tri(MAT)], function(x) strsplit(x, " ")) 
ind <- lapply(combs, function(x) match(x, names(df))) 

plotter <- function(cn) { #start junky function 
    NAMES <- colnames(df)[cn] 
    df2 <- df[cn] 
    names(df2)<- c('x1', 'x2') 
    p <- ggplot(data=df2, aes(x1, x2)) + geom_point() + theme_bw() + 
     scale_x_continuous(name=NAMES[1]) + 
     scale_y_continuous(name=NAMES[2]) 
     dev.new() 
     print(p) 
} #end of junky function 

lapply(ind, function(x) plotter(cn=x)) 

편집 : 어쩌면 다른 사람이 더 나은 뭔가가

x <- match(names(df)[-1], names(df)) 
MAT <- outer(x, x, paste) 
combs <- t(sapply(MAT[lower.tri(MAT)], function(x) as.numeric(unlist(strsplit(x, " "))))) 

plotter <- function(cn) { 
    NAMES <- colnames(df)[cn] 
    df2 <- df[cn] 
    names(df2)<- c('x1', 'x2') 
    p <- ggplot(data=df2, aes(x1, x2)) + geom_point() + theme_bw() + 
     scale_x_continuous(name=NAMES[1]) + 
     scale_y_continuous(name=NAMES[2]) 
     dev.new() 
     print(p) 
} 

apply(combs, 1, function(x) plotter(cn=x)) 
+0

답변 해 주셔서 감사합니다. 나는 당신이 대답을 게시 할 때 편집 중이었습니다. 내 편집 된 질문을 참조하십시오. 감사 – MYaseen208

관련 문제