Skip to content

Instantly share code, notes, and snippets.

@timtreis
Created June 21, 2022 07:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timtreis/8fe84a08ff13d3d96c87bc7be63173bb to your computer and use it in GitHub Desktop.
Save timtreis/8fe84a08ff13d3d96c87bc7be63173bb to your computer and use it in GitHub Desktop.
Method to extract the title from a ggplot legend
library("visR")
get_legend_title <- function(gg) {
ggb <- ggplot2::ggplot_build(gg)
ggt <- ggplot2::ggplot_gtable(ggb)
legend_grob_id <- which(sapply(ggt$grobs, function(x) x$name) == "guide-box")
legend_grob <- ggt$grobs[[legend_grob_id]]
legend_title_id <- which(sapply(legend_grob$grobs[[1]]$layout$name, function(x) x) == "title")
legend_gtree <- legend_grob$grobs[[1]]$grobs[[legend_title_id]]
legend_title <- legend_gtree$children[[1]]$children[[1]]$label
return(legend_title)
}
gg <- adtte %>%
visR::estimate_KM("SEX") %>%
visR::visr()
get_legend_title(gg) #-> "Sex"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment