plot_legend.R 2.70 KiB
#' @title Plot a legend independently of a map
#'
#' @details
#' \subsection{path specification}{
#' Depending on the extension a device is chosen.
#' \itemize{
#'   \item{\strong{pdf}: grDevices::cairo_pdf}
#'   \item{\strong{png}: grDevices::png}
#'   \item{\strong{svg}: grDevices::svg}
#' }
#' If path is NULL, standard plotting is used. If an extension is not managed,
#' an error is raised.
#' }
#' @param dataset_legend list of parameters to be passed to legend
#' @param path character, the name of the file to save the plot. Graphical
#'  device is chosen depending on extension. See details.
#' @param horiz logical, should the legend be horizontal
#' @param add logical, should the legend be added to the current plot
#' @return Nothing useful.
#' @export plot_legend
#' @encoding UTF-8
#' @author Frédéric Grelot
#' @examples
#' dataset_legend = list(
#'  title = "Beatutiful legend",
#'  legend = c("red circle", "black square", "blue diamond"),
#'  pch = 21:23,
#'  pt.bg = c("red", "black", "blue")
#' )
#' plot_legend(dataset_legend)
#' plot_legend(dataset_legend, horiz = FALSE)
plot_legend = function(dataset_legend, path = NULL, horiz = TRUE, add = FALSE) {
    dataset_legend[["horiz"]] = horiz
    if (add == FALSE) {
        if (!is.null(path)) {
            switch(
                EXPR = tolower(tools::file_ext(path)),
                "pdf" = grDevices::cairo_pdf(path),
                "png" = grDevices::png(path),
                "jpg" = grDevices::jpeg(path),
                "svg" = grDevices::svg(path),
                stop(sprintf("%s not recognized", tolower(tools::file_ext(path))))
            on.exit(grDevices::dev.off())
            dataset_legend[["x"]] = "center"
            graphics::par(mai = c(0, 0, 0, 0))
            plot(NULL, axes = FALSE, ann = FALSE, xlim = 0:1, ylim = 0:1)
            dimension = do.call(graphics::legend, dataset_legend)
            grDevices::dev.off()
            width = dimension[["rect"]][["w"]]
            height = dimension[["rect"]][["h"]]
            switch(
                EXPR = tolower(tools::file_ext(path)),
                "pdf" = grDevices::cairo_pdf(path, width = width * 7.5, height = height * 7.5),
                "png" = grDevices::png(path, width = round(width * 500), height = round(height * 500)),
                "jpg" = grDevices::jpeg(path, width = round(width * 500), height = round(height * 500)),
                "svg" = grDevices::svg(path, width = width * 7.5, height = height * 7.5)
717273747576
old_par = graphics::par(mai = c(0, 0, 0, 0)) dataset_legend[["x"]] = "center" plot(NULL, axes = FALSE, ann = FALSE, xlim = 0:1, ylim = 0:1) } do.call(graphics::legend, dataset_legend) }