首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在ggplot2中只绘制图例?

如何在ggplot2中只绘制图例?
EN

Stack Overflow用户
提问于 2012-08-20 23:55:45
回答 4查看 40.7K关注 0票数 49

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

此时,我能想到的是使用ggplot2仅打印图例并隐藏条形图。有什么方法可以直接输出图例吗?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-08-21 00:52:02

这里有两种方法:

设置绘图

代码语言:javascript
运行
复制
library(ggplot2) 
library(grid)
library(gridExtra) 

my_hist <- ggplot(diamonds, aes(clarity, fill = cut)) + 
    geom_bar() 

Cowplot方法

代码语言:javascript
运行
复制
# 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

代码语言:javascript
运行
复制
## 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)。

票数 71
EN

Stack Overflow用户

发布于 2017-05-31 17:25:28

Cowplot很方便地添加了一个函数来提取图例。以下内容直接取自手册。

代码语言:javascript
运行
复制
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)))
票数 25
EN

Stack Overflow用户

发布于 2019-05-30 17:44:59

我使用了ggpubr包-让它变得非常简单!

https://rpkgs.datanovia.com/ggpubr/reference/get_legend.html

代码语言:javascript
运行
复制
# Extract the legend. Returns a gtable
leg <- get_legend(p)

# Convert to a ggplot and print
as_ggplot(leg)
票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12041042

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档