R/as-ggplot.R

Defines functions as.ggplot_internal as.ggplot

Documented in as.ggplot

##' convert plot to ggplot object
##'
##'
##' @title as.ggplot
##' @param plot base or grid plot, or graphic generated by ggplot, lattice, etc.
##' @param scale scale of the plot to be drawn
##' @param hjust horizontal adjustment
##' @param vjust vertical adjustment
##' @param angle angle to rotate plot
##' @param ... additional parameters passed to as.grob
##' @importFrom ggplot2 ggplot
##' @importFrom ggplot2 aes_
##' @importFrom ggplot2 geom_blank
##' @importFrom ggplot2 annotation_custom
##' @importFrom ggplot2 theme_void
##' @importFrom ggplot2 scale_x_continuous
##' @importFrom ggplot2 scale_y_continuous
##' @return ggplot object
##' @importFrom grid viewport
##' @export
##' @examples
##' as.ggplot(~barplot(1:10))
##' @author Guangchuang Yu
as.ggplot <- function(plot, scale = 1, hjust = 0, vjust = 0, angle = 0, ...) {
    ## plot_expr <- quo_name(enexpr(plot))
    ## if (is.null(plot)) {
    ##     plot <- as.grob(plot_expr)
    ## }

    if (angle == 0) {
        return(as.ggplot_internal(plot = plot,
                                  scale = scale,
                                  hjust = hjust,
                                  vjust = vjust,
                                  ...))
    }

    g <- grid2grob(print(as.ggplot_internal(plot, ...),
                         newpage = TRUE,
                         vp = viewport(x = .5 + hjust,
                                       y = .5 + vjust,
                                       angle = angle,
                                       width = scale,
                                       height = scale)
                         ))
    as.ggplot(g)
}


as.ggplot_internal <- function(plot, scale = 1, hjust = 0, vjust = 0, ...) {
    ymin <- xmin <- 1 - scale
    xmax <- ymax <- scale

    ggplot(data.frame(x = 0:1, y = 0:1), aes_(x = ~x, y = ~y)) +
        geom_blank() +
        scale_x_continuous(limits = c(0,1), expand = c(0, 0)) +
        scale_y_continuous(limits = c(0,1), expand = c(0, 0)) +
        annotation_custom(as.grob(plot, ...),
                          xmin = xmin + hjust,
                          xmax = xmax + hjust,
                          ymin = ymin + vjust,
                          ymax = ymax + vjust)  +
        theme_void() 
}
GuangchuangYu/ggplotify documentation built on Feb. 10, 2024, 9:49 a.m.