如何在ggplot2中只绘制图例?

59

我正在使用igraph,并为我的节点添加了颜色标签。我想添加一个图例来说明每种颜色代表的含义。

目前我能想到的方法是使用ggplot2来仅打印图例并隐藏条形图。是否有一种只输出图例的方法?


哦,是的,我没有看到你说igraph。如果我没记错的话,那是在基础包里面的,而ggplot2使用grid。最好像Gabor在下面讨论的那样自己制作图例。他显然比我读得更仔细。 - Tyler Rinker
4个回答

81

这里有两种方法:

设置图表

library(ggplot2) 
library(grid)
library(gridExtra) 

my_hist <- ggplot(diamonds, aes(clarity, fill = cut)) + 
    geom_bar() 

Cowplot方案

# Using the cowplot package
legend <- cowplot::get_legend(my_hist)

grid.newpage()
grid.draw(legend)

自制方法

恶意抄袭自:在 ggplot2 直方图中插入图例下方的表格

## Function to extract legend
g_legend <- function(a.gplot){ 
    tmp <- ggplot_gtable(ggplot_build(a.gplot)) 
    leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box") 
    legend <- tmp$grobs[[leg]] 
    legend
} 

legend <- g_legend(my_hist) 

grid.newpage()
grid.draw(legend) 

这是在2018年5月31日使用 reprex 包 (v0.2.0) 创建的。


虽然我无法使用视口函数编辑图例和igraph对象的大小。 - Buthetleon
6
我的传奇有很大的页边距挡住了视线,是我忘记了什么吗? - Lilith-Elina
请查看主题并更改图例背景的透明度。如果这不起作用,请使用可重现的示例和您正在尝试的代码提出自己的问题。 - Tyler Rinker
我建议将 cowplot 选项突出显示,因为它是最直接和高效的答案。 - Garini

30

Cowplot方便地添加了提取图例的功能。以下内容直接摘自手册。

library(ggplot2)
library(cowplot)
p1 <- ggplot(mtcars, aes(mpg, disp)) + geom_line()
plot.mpg <- ggplot(mpg, aes(x = cty, y = hwy, colour = factor(cyl))) + geom_point(size=2.5)

# Note that these cannot be aligned vertically due to the legend in the plot.mpg
ggdraw(plot_grid(p1, plot.mpg, ncol=1, align='v'))

# now extract the legend
legend <- get_legend(plot.mpg)

# and replot suppressing the legend
plot.mpg <- plot.mpg + theme(legend.position='none')

# Now plots are aligned vertically with the legend to the right
ggdraw(plot_grid(plot_grid(p1, plot.mpg, ncol=1, align='v'),
                 plot_grid(NULL, legend, ncol=1),
                 rel_widths=c(1, 0.2)))

25

1
虽然有很多新的软件包与之一起发布,但它运行得非常顺畅 :) - Mathias711

3
我正在对图中的顶点进行颜色编码,并希望尽可能简单、优雅和快速地生成图例。
我相信最快的方法是在使用ggplot2之前单独生成图例,然后使用viewportlayout()将图例“粘贴”到与igraph相同的图中。
在这种方法中,不需要在plot.igraph()函数中调用rescaleasp参数。
使用g_legend函数在一个具有两列的数据框leg上,其中x是适当的顶点属性,y是我的igraph图中使用的十六进制颜色代码,我已经完成了以下操作。
我的igraph对象是t8g
legend <- g_legend(leg)
vpleg <- viewport(width = 0.1, height = 0.1, x=0.85,y=0.5)
layout(matrix(c(1,2),1,2,byrow=T),widths=c(3,1))
plot(t8g,edge.width=1,edge.arrow.size=0.1,vertex.label.cex=0.2,main="b2_top10")
pushViewport(vpleg)
grid.draw(legend)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接