如何绘制只是GGPLOT2传说?(How to plot just the legends in g

2019-06-17 19:05发布

我目前用的igraph工作,并标有颜色我顶点。 我想补充一个传说指出哪些每种颜色代表。

我可以在此时想到的是使用GGPLOT2只打印传说和隐藏柱状图。 有没有办法,只是输出的传说?

Answer 1:

这里有两个方法:

设置绘图

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



Answer 2:

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


Answer 3:

我是颜色编码在图中的顶点,想要简单地生成一个传奇,典雅,并以最快的速度,我可以。

要做到这一点,最快的方法我开始相信是生成图例的igraph使用单独使用GGPLOT2传说到同一个情节之前“粘贴” viewportlayout()

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


文章来源: How to plot just the legends in ggplot2?
标签: r ggplot2 igraph