diff --git a/.gitignore b/.gitignore index 6e8243e..ac8fba0 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,11 @@ *.pyc __pycache__ */__pycache__ +mcsm_analysis_fixme +del +examples +example +scratch +test +plotting_test +scripts_old diff --git a/scripts/plotting/legend_adjustment.R b/scripts/plotting/legend_adjustment.R new file mode 100644 index 0000000..b236a72 --- /dev/null +++ b/scripts/plotting/legend_adjustment.R @@ -0,0 +1,37 @@ + +library(ggplot2) +library(gtable) +library(lemon) +# https://stackoverflow.com/questions/54438495/shift-legend-into-empty-facets-of-a-faceted-plot-in-ggplot2 + +shift_legend2 <- function(p) { + # check if p is a valid object + if(!(inherits(p, "gtable"))){ + if(inherits(p, "ggplot")){ + gp <- ggplotGrob(p) # convert to grob + } else { + message("This is neither a ggplot object nor a grob generated from ggplotGrob. Returning original plot.") + return(p) + } + } else { + gp <- p + } + + # check for unfilled facet panels + facet.panels <- grep("^panel", gp[["layout"]][["name"]]) + empty.facet.panels <- sapply(facet.panels, function(i) "zeroGrob" %in% class(gp[["grobs"]][[i]]), + USE.NAMES = F) + empty.facet.panels <- facet.panels[empty.facet.panels] + + if(length(empty.facet.panels) == 0){ + message("There are no unfilled facet panels to shift legend into. Returning original plot.") + return(p) + } + + # establish name of empty panels + empty.facet.panels <- gp[["layout"]][empty.facet.panels, ] + names <- empty.facet.panels$name + + # return repositioned legend + reposition_legend(p, 'center', panel=names) +}