2013-07-02 5 views
1

여러 범례를 표로 표시하려고합니다. 예 :ggplot2 : 테이블로 여러 범례

library(ggplot2) 

dat <- data.frame(
    x = rep(1:4, 4), 
    y = c(1:4, 2:5, 3:6, 4:7), 
    a = rep(rep(c("a1", "a2"), each=4), 2), 
    b = rep(c("b1", "b2"), each=8)) 

ggplot(dat, aes(x=x, y=y, colour=b, shape=a)) + 
    geom_point()+ facet_wrap(~ b) 

다른 색상과 모양으로 여러 범례를 가져올 수 있습니다. 하지만 내 전설을 보여주고 싶습니다.

 b1 | b2 
-------------- 
a1 | o | o 
a2 |^|^

어떻게 전설을 그릴 수 있습니까?

답변

0

다음은 한 예입니다 :

p <- ggplotGrob(ggplot(dat, aes(x=x, y=y, colour=b, shape=a)) + 
    geom_point()+ facet_wrap(~ b) + theme(legend.position = "none")) 

leg <- ggplotGrob(ggplot(unique(subset(dat, select = a:b)), aes(a, b, colour=b, shape=a)) + geom_point() + 
    coord_equal() + 
    theme_minimal() + 
    theme(legend.position = "none", axis.ticks = element_blank(), axis.title = element_blank())) 

library(gtable) 
grid.newpage() 
pushViewport(vp = viewport(width = 0.8, x = 0.4)) 
grid.draw(p) 
popViewport() 
pushViewport(vp = viewport(width = 0.2, x = 1-0.1)) 
grid.draw(leg) 
popViewport() 

enter image description here

그리고 당신은 theme를 사용자 지정하여 모양을 조정할 수 있습니다.

+0

당신은 a와 b를 뒤집고 패싯 제목을 사용하여 범례 위에 레이블을 붙일 수 있습니다. – baptiste

+0

또한, 이것은 미친 짓입니다. 좋은 방법으로. '전설적인 '패키지를 써야한다. – baptiste

관련 문제