2014-07-23 1 views
5
여기

참조 플롯 :ggplot2, 두 개의 눈금을 동일한 플롯에 적용 하시겠습니까? 하향식 barplot

( here에서)

enter image description here

어떻게 ggplot2를 사용하여 barplot의 상단과 하단 부분을 모두 재현 할 수 있습니까? I는 Y에 대한 규모가 역전 다른 geom_bar() 같은 다른 geom_ 추가하면

예를 들어, I 그러나 지금

ggplot(data.frame(x=rnorm(1000, 5)), aes(x=x)) + geom_bar() + scale_y_reverse() 

와 상부를 생성 할 수있다. 특정 geom_에만 scale_y_reverse()을 적용 할 수 있습니까?

답변

4

ggplot은 하나의 y 축 스케일 만 가질 수 있습니다. 가장 쉬운 방법은 기본적으로 자신의 데이터를 재구성하는 것입니다. 여기서 우리는 을 사용하여 언제 어디서나 데이터를 그릴 수 있으며 그룹 시간에 데이터를 조절할 수 있습니다. 여기에 예제가 있습니다

#sample data 
dd<-data.frame(
    year=rep(2000:2014, 2), 
    group=rep(letters[1:2], each=15), 
    count=rpois(30, 20) 
) 

이제 우리는 그것을 플로팅 할 수 있습니다. 하지만 먼저, 우리는

ggplot(dd) + 
    geom_rect(aes(xmin=year-.4, xmax=year+.4, 
    ymin=ifelse(group=="a", 0, height-count), 
    ymax=ifelse(group=="a", count, height), fill=group)) + 
    scale_y_continuous(expand=c(0,0)) 

음모 방법의 여기 공간

height <- ceiling(max(tapply(dd$count, dd$year, sum))*1.10) 

을 조금 년에 최대 높이를 발견하고 추가하여 상단 바 오프셋을 정의하자 그리고 우리에게

을 줄 것이다

enter image description here

+0

매우 영리 해킹! – Vlo

8

또 다른 옵션은 두 개의 플롯을하고 삐걱 삐걱 소리에서 arrangeGrob로를 결합하는 것입니다 xtra 패키지. 작의 마진을 가지고 노는 후,보기 흉하지 않은 것으로 도착할 수 있습니다.

library(gridExtra) 
library(ggplot2) 

set.seed(100) 
p2 <- ggplot(data.frame(x=rnorm(1000, 5)), aes(x=x)) + geom_bar() + theme(plot.margin=unit(c(0,0,0,0), 'lines')) 
p1 <- p2 + scale_y_reverse() + 
    theme(plot.margin=unit(c(0, 0, -.8, 0), 'lines'), axis.title.x=element_blank(), 
      axis.text.x=element_blank(), axis.ticks.x=element_blank()) 

p <- arrangeGrob(p1, p2) 
print(p) 

enter image description here

+0

유령 downvoter! 너의 이름을 말하고 너 자신을 설명하라. –

관련 문제