shift_legend: Shift the Legend of a Facetted Plot to an Empty Facet

View source: R/shift_legend_function.R

shift_legendR Documentation

Shift the Legend of a Facetted Plot to an Empty Facet

Description

This function places the legend of a facetted plot with an uneven number of facets into the empty space (the empty facet area).
This function is taken from stack overflow: https://stackoverflow.com/questions/54438495/shift-legend-into-empty-facets-of-a-faceted-plot-in-ggplot2
See also https://stackoverflow.com/questions/28496764/add-textbox-to-facet-wrapped-layout-in-ggplot2
and the cowplot package https://cran.r-project.org/web/packages/cowplot/vignettes/introduction.html

Usage

shift_legend(p)

Arguments

p

A ggplot object.

Examples


p <- (ggplot2::ggplot(diamonds, aes(x = carat, fill = cut)) 
      + geom_density(position = "stack") + facet_wrap(~ color) )
library(grid)
grid.draw(shift_legend(p))

p.new <- p +
  guides(fill = guide_legend(title.position = "top",
                            label.position = "bottom",
                            nrow = 1)) +
  theme(legend.direction = "horizontal")
grid.draw(shift_legend(p.new))

JenC36/JACtools documentation built on Oct. 20, 2024, 8:05 a.m.