如何在ggplot2中只绘制传说?

问题描述 投票:29回答:4

我目前正在使用igraph,并将颜色标记为我的顶点。我想添加一个图例指示每种颜色代表什么。

我现在能想到的是使用ggplot2只打印图例并隐藏条形图。有没有办法输出传奇?

r ggplot2 igraph
4个回答
42
投票

这有两种方法:

设置图

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)

本土方法

无耻地偷走了:Inserting a table under the legend in a ggplot2 histogram

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

reprex package创建于2018-05-31(v0.2.0)。


18
投票

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

3
投票

我对图表中的顶点进行了颜色编码,并希望尽可能简单,优雅,快速地生成图例。

最快的方法我已经开始相信使用ggplot2分别生成图例,然后使用viewportlayout()将图例“粘贴”到与igraph相同的图中

在这种方法中,没有必要在rescale函数中调用aspplot.igraph()论证。

在data.frame上使用g_legend函数,leg,有2列,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)

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)
© www.soinside.com 2019 - 2024. All rights reserved.