Add a common legend

筅森魡賤 提交于 2019-12-06 12:32:13

lemon or cowplot packages have really nice built-in functions to deal with shared legend between plots

example from lemon package

library(ggplot2)
library(grid)
library(gtable)
library(lemon)

dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
d <- ggplot(dsamp, aes(carat, price)) +
  geom_point(aes(colour = clarity)) +
  theme(legend.position = c(0.06, 0.75))

d3 <- d + 
  facet_wrap(~cut, ncol=3) + 
  scale_color_discrete(guide=guide_legend(ncol=3))

# Use gtable_show_names to display the names of the facetted panels
gtable_show_names(d3)

# So to place the legend in a specific panel, give its name:
reposition_legend(d3, 'center', panel='panel-3-2')

example from cowplot package

library(cowplot)

# Make three plots.
# We set left and right margins to 0 to remove unnecessary spacing in the
# final plot arrangement.
p1 <- qplot(carat, price, data=dsamp, colour=clarity) +
  theme(plot.margin = unit(c(6,0,6,0), "pt"))

p2 <- qplot(depth, price, data=dsamp, colour=clarity) +
  theme(plot.margin = unit(c(6,0,6,0), "pt")) + ylab("")

p3 <- qplot(color, price, data=dsamp, colour=clarity) +
  theme(plot.margin = unit(c(6,0,6,0), "pt")) + ylab("")

# arrange the three plots in a single row
prow <- plot_grid( p1 + theme(legend.position="none"),
           p2 + theme(legend.position="none"),
           p3 + theme(legend.position="none"),
           align = 'vh',
           labels = c("A", "B", "C"),
           hjust = -1,
           nrow = 1
           )

# extract the legend from one of the plots
# (clearly the whole thing only makes sense if all plots
# have the same legend, so we can arbitrarily pick one.)
legend <- get_legend(p1)

# add the legend to the row we made earlier. Give it one-third of the width
# of one plot (via rel_widths).
p <- plot_grid( prow, legend, rel_widths = c(3, .3))
p

Created on 2018-04-14 by the reprex package (v0.2.0).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!