繁体   English   中英

如何 plot 只是 ggplot2 中的传说?

[英]How to plot just the legends in ggplot2?

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

此时我能想到的是使用 ggplot2 仅打印图例并隐藏条形 plot。 有没有办法只是 output 传说?

这里有2种方法:

设置情节

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) 

reprex 包(v0.2.0) 于 2018 年 5 月 31 日创建。

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

我使用了 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)

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

我认为最快的方法是使用 ggplot2 单独生成图例,然后使用viewportlayout()将图例“粘贴”到与 igraph 相同的图中

在这种方法中,没有必要再调用rescaleasp arguements在plot.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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM