如何仅绘制 ggplot2 中的图例? [英] How to plot just the legends in ggplot2?

查看:46
本文介绍了如何仅绘制 ggplot2 中的图例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm currently working with igraph and have colour labelled my vertices. I would like to add a legend Indicating what each colour represents.

此时我能想到的是使用 ggplot2 仅打印图例并隐藏条形图.有没有办法只输出图例?

What I can think of at this point is to use ggplot2 to print only the legend and hide a bar plot. Is there a way to just output the legend?

推荐答案

这里有两种方法:

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 日创建.

Created on 2018-05-31 by the reprex package (v0.2.0).

这篇关于如何仅绘制 ggplot2 中的图例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆