Ggplot2:多个图例作为表 [英] ggplot2: multiple legend as table

查看:17
本文介绍了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 | ^  |  ^

这样怎么画图例?

推荐答案

举个例子:

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()

您可以通过自定义theme来调整外观。

这篇关于Ggplot2:多个图例作为表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆