如何绘制ggplot2中的传说? [英] How to plot just the legends in ggplot2?

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

问题描述

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

我现在可以想到的是,使用ggplot2仅打印图例并隐藏一个条形图。
有没有一种方法可以输出图例?

解决方案

无耻地从

b
$ b

  library(ggplot2);库(gridExtra);库(grid)
my_hist< -ggplot(diamonds,aes(clarity,fill = cut))+ geom_bar()

#create嵌入表
my_table< - tableGrob (菱形)[,1:3],
gpar.coretext = gpar(fontsize = 8),gpar.coltext = gpar(fontsize = 8),
gpar.rowtext = gpar(fontsize = 8) )

#Extract Legend
g_legend< -function(a.gplot){
tmp< - ggplot_gtable(ggplot_build(a.gplot))
leg< - (sapply(tmp $ grobs,function(x)x $ name)==guide-box)
legend< - tmp $ grobs [[leg]]
return(legend)}

legend< - g_legend(my_hist)
grid.draw(legend)


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

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?

解决方案

Shamelessly stolen from: Inserting a table under the legend in a ggplot2 histogram

library(ggplot2); library(gridExtra); library(grid)
my_hist<-ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar() 

#create inset table 
my_table<- tableGrob(head(diamonds)[,1:3], 
    gpar.coretext =gpar(fontsize=8), gpar.coltext=gpar(fontsize=8),  
    gpar.rowtext=gpar(fontsize=8)) 

#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]] 
  return(legend)} 

legend <- g_legend(my_hist) 
grid.draw(legend) 

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

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