2013-07-02 104 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