Skip to content

Instantly share code, notes, and snippets.

@zeehio
Last active September 28, 2017 15:32
Show Gist options
  • Select an option

  • Save zeehio/33fc79df59b9b4373e6d9ec5c12729c7 to your computer and use it in GitHub Desktop.

Select an option

Save zeehio/33fc79df59b9b4373e6d9ec5c12729c7 to your computer and use it in GitHub Desktop.
Function to add a space between the legend title and the legend values on a ggplot plot
#' Add space between the legend title and the legend items
#' @param gplt A plot created with ggplot
#' @param x How much space to add, given in x_unit units (default 0.5 lines)
#' @param x_unit Unit of x, "line" by default
#' @return A gtable object that can be plotted using plot()
#' @examples
#' library(ggplot2)
#' gplt <- ggplot(iris) + geom_point(aes(x=Sepal.Length, y = Sepal.Width, color = Species))
#' plt_gtable <- add_legend_title_space(gplt)
#' plot(plt_gtable)
add_legend_title_space <- function(gplt, x=0.5, x_unit="line") {
p_table <- ggplot2::ggplot_gtable(ggplot2::ggplot_build(gplt))
# Adapted from
# https://stackoverflow.com/a/32276573/446149
## extract legend
leg <- which(vapply(p_table$grobs, function(x) x$name, character(1)) == "guide-box")
# The legend is represented as a table
legend_table <- p_table$grobs[[leg]]$grobs[[1]]
# Where is the title?
leg_title <- which(legend_table$layout$name == "title")
## this is the tricky part !
## adds a row after the title
p_table$grobs[[leg]]$grobs[[1]] <-
gtable::gtable_add_rows(p_table$grobs[[leg]]$grobs[[1]],
grid::unit(x, x_unit),
pos=p_table$grobs[[leg]]$grobs[[1]]$layout$b[leg_title])
return(p_table)
}
@zeehio

zeehio commented Sep 28, 2017

Copy link
Copy Markdown
Author

Example:

imatge

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment