如何在ggplot2中只绘制传说?

But*_*eon 37 r igraph ggplot2

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

我现在能想到的是使用ggplot2只打印图例并隐藏条形图.有没有办法输出传奇?

Tyl*_*ker 49

无耻地偷窃:在ggplot2直方图中插入图例下的表格

library(ggplot2) 
library(grid)
library(gridExtra) 

my_hist <- ggplot(diamonds, aes(clarity, fill = cut)) + 
    geom_bar() 
Run Code Online (Sandbox Code Playgroud)

reprex包(v0.2.0)创建于2018-05-31 .

  • 我的传奇有巨大的利润阻碍了我忘了什么? (5认同)

r.b*_*bot 18

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)))
Run Code Online (Sandbox Code Playgroud)


glh*_*rsh 5

我使用了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)
Run Code Online (Sandbox Code Playgroud)