2013-08-29 3 views
2

다음과 같은 간단한 그림이 있다고 가정 해 봅시다.ggplot (R)에 두 개의 평행 축을 표시합니다.

library(ggplot2) 
df = data.frame(y=c(0,1.1,2.3,3.1,2.9,5.8,6,7.4,8.2,9.1),x=seq(1,100, length.out=10)) 
ggplot(df,aes(x=x,y=y)) + geom_point() 

x 완벽 z와 상관 관계. 의 관계는 다음과 같습니다

df = cbind(df,1.23/df$x^2) 

질문은 다음과 같습니다 :

내가 두 변수를 표시 할 수있는 방법 xz 하나의 x 축 Constant=x^2*z=1.23가 그러므로 나는이 같은 data.frame를 다시 작성할 수 ? 그래프 하단에는 하나, 그래프 상단에는 하나 또는 하단에 모두있을 수 있습니다.

+1

는 ggplot2에 수 없습니다. 그리드로 해킹 당할 수는 있지만 해밀리가 카멜을 죽일 때마다 해킹 당할 수 있습니다. – baptiste

+0

보조 축에서 'ggplot2'를 사용하지 않으려면. 기본 그래픽 (또는 격자)을 사용하면 훨씬 쉽습니다. – Roland

답변

6

다음은 위험한 시도입니다. 이전 버전의 로그 스케일은 입니다.입니다.

library(ggplot2) 
df = data.frame(y=c(0,1.1,2.3,3.1,2.9,5.8,6,7.4,8.2,9.1), 
       x=seq(1,100, length.out=10)) 
df$z = 1.23/df$x^2 


## let's at least remove the gridlines 
p1 <- ggplot(df,aes(x=x,y=y)) + geom_point() + 
    scale_x_continuous(expand=c(0,0)) + 
    theme(panel.grid.major=element_blank(), 
     panel.grid.minor = element_blank()) 

## make sure both plots have expand = c(0,0) 
## otherwise data and top-axis won't necessarily be aligned... 
p2 <- ggplot(df,aes(x=z,y=y)) + geom_point() + 
    scale_x_continuous(expand=c(0,0)) 

library(gtable) 
g1 <- ggplotGrob(p1) 
g2 <- ggplotGrob(p2) 
tmp <- gtable_filter(g2, pattern="axis-b") 

## ugly tricks to extract and reshape the axis 
axis <- tmp[["grobs"]][[1]][["children"]][["axis"]] # corrupt the children 
axis$layout <- axis$layout[2:1,] 
axis$grobs[[1]][["y"]] <- axis$grobs[[1]][["y"]] - unit(1,"npc") + unit(0.15,"cm") 
## back to "normality"  

g1 <- gtable_add_rows(g1, sum(tmp$heights), 2) 
gtableAddGrobs <- gtable_add_grob # alias, making sure @!hadley doesn't see this 
g1 <- gtableAddGrobs(g1, 
        grobs=list(gtable_filter(g2, pattern="xlab"),axis), 
        t=c(1,3), l=4) 
grid.newpage() 
grid.draw(g1) 

enter image description here

관련 문제