我正在使用igraph,并为我的节点添加了颜色标签。我想添加一个图例来说明每种颜色代表的含义。
目前我能想到的方法是使用ggplot2来仅打印图例并隐藏条形图。是否有一种只输出图例的方法?
这里有两种方法:
library(ggplot2)
library(grid)
library(gridExtra)
my_hist <- ggplot(diamonds, aes(clarity, fill = cut)) +
geom_bar()
# 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) 创建的。
cowplot
选项突出显示,因为它是最直接和高效的答案。 - GariniCowplot方便地添加了提取图例的功能。以下内容直接摘自手册。
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)))
我使用了ggpubr包 - 这使得操作非常简单!
https://rpkgs.datanovia.com/ggpubr/reference/get_legend.html
# Extract the legend. Returns a gtable
leg <- get_legend(p)
# Convert to a ggplot and print
as_ggplot(leg)
viewport
和layout()
将图例“粘贴”到与igraph相同的图中。plot.igraph()
函数中调用rescale
或asp
参数。leg
上,其中x是适当的顶点属性,y是我的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)