ggrastr/0000755000176200001440000000000014436033072011725 5ustar liggesusersggrastr/NAMESPACE0000644000176200001440000000071114435743246013155 0ustar liggesusers# Generated by roxygen2: do not edit by hand S3method(makeContext,rasteriser) S3method(rasterise,Layer) S3method(rasterise,ggplot) S3method(rasterise,list) export(geom_beeswarm_rast) export(geom_boxplot_jitter) export(geom_jitter_rast) export(geom_point_rast) export(geom_quasirandom_rast) export(geom_tile_rast) export(geom_violin_rast) export(rasterise) export(rasterize) export(theme_pdf) import(ggbeeswarm) import(ggplot2) importFrom(grid,makeContext) ggrastr/LICENSE0000644000176200001440000000010614435743246012741 0ustar liggesusersYEAR: 2020 COPYRIGHT HOLDER: Viktor Petukhov ggrastr/README.md0000644000176200001440000000602514435743246013221 0ustar liggesusers[![](https://circleci.com/gh/VPetukhov/ggrastr.svg?style=svg)](https://app.circleci.com/pipelines/github/VPetukhov/ggrastr) [![CRAN status](https://www.r-pkg.org/badges/version/ggrastr)](https://cran.r-project.org/package=ggrastr) [![CRAN downloads](https://cranlogs.r-pkg.org/badges/ggrastr)](https://cran.r-project.org/package=ggrastr) # ggrastr Rasterize only specific layers of a [ggplot2 plot](https://ggplot2.tidyverse.org/) (for instance, large scatter plots with many points) while keeping all labels and text in vector format. This allows users to keep plots within a reasonable size limit without losing the vector properties of scale-sensitive information. ## Installation To install the stable version from [CRAN](https://CRAN.R-project.org/package=ggrastr), use: ```r install.packages('ggrastr') ``` To install the latest version, use: ```r install.packages('devtools') devtools::install_github('VPetukhov/ggrastr', build_vignettes = TRUE) ``` ## Rasterize any ggplot2 layer Note that with `ggrastr` version 0.2.0, any ggplot2 geom provided by the user can be rasterized with the function `rasterise()`. Furthermore, when the aspect ratio is distorted, points are rendered without distortion. For more details and examples, see the **vignettes:** * [HTML version](https://htmlpreview.github.io/?https://raw.githubusercontent.com/VPetukhov/ggrastr/main/doc/Raster_geoms.html) * [Markdown version](https://github.com/VPetukhov/ggrastr/blob/main/vignettes/Raster_geoms.md) ## Geoms provided We also provide wrappers for several geoms to guarantee compatibility with an older version of `ggrastr`. However, we encourage users to use the `rasterise()` function instead. * `geom_point_rast`: raster scatter plots * `geom_jitter_rast`: raster jittered scatter plots * `geom_boxplot_jitter`: boxplots that allows to jitter and rasterize outlier points * `geom_tile_rast`: raster heatmap * `geom_beeswarm_rast`: raster [bee swarm plots](https://github.com/eclarke/ggbeeswarm#geom_beeswarm) * `geom_quasirandom_rast`: raster [quasirandom scatter plot](https://github.com/eclarke/ggbeeswarm#geom_quasirandom) ## Troubleshooting If your R session crashes when you try to render a rasterized plot, it's probably the case that your version of Cairo was built for another version of R (see [Upgrading to a new version of R](https://shiny.rstudio.com/articles/upgrade-R.html)). To check if you are using a proper version, run the command below and ensure that the "Built" version is the same as your R version. ```r pkgs <- as.data.frame(installed.packages(), stringsAsFactors = FALSE, row.names = FALSE) pkgs[pkgs$Package == 'Cairo', c("Package", "LibPath", "Version", "Built")] ``` To ensure that Cairo works, try running `Cairo::Cairo(type='raster'); dev.off()` and check if it crashes your R session. ## Citation If you find `ggrastr` useful for your publication, please cite: ``` Viktor Petukhov, Teun van den Brand and Evan Biederstedt (2021). ggrastr: Raster Layers for 'ggplot2'. R package version 1.0.1. https://CRAN.R-project.org/package=ggrastr ``` ggrastr/man/0000755000176200001440000000000014436024313012476 5ustar liggesusersggrastr/man/geom_jitter_rast.Rd0000644000176200001440000000355314436024313016334 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/geom-jitter-rast.R \name{geom_jitter_rast} \alias{geom_jitter_rast} \title{This geom is similar to \code{\link[ggplot2]{geom_jitter}}, but creates a raster layer} \usage{ geom_jitter_rast( ..., raster.dpi = getOption("ggrastr.default.dpi", 300), dev = "cairo", scale = 1 ) } \arguments{ \item{...}{Other arguments passed on to \code{\link[ggplot2:layer]{layer()}}. These are often aesthetics, used to set an aesthetic to a fixed value, like \code{colour = "red"} or \code{size = 3}. They may also be parameters to the paired geom/stat.} \item{raster.dpi}{integer Resolution of the rastered image in dots per inch (default=300).} \item{dev}{string Specifies the device used, which can be one of: \code{"cairo"}, \code{"ragg"} or \code{"ragg_png"} (default="cairo").} \item{scale}{numeric Scaling factor to modify the raster object size (default=1). The parameter 'scale=1' results in an object size that is unchanged, 'scale'>1 increase the size, and 'scale'<1 decreases the size. These parameters are passed to 'height' and 'width' of grid::grid.raster(). Please refer to 'rasterise()' and 'grid::grid.raster()' for more details.} } \value{ geom_point_rast plot with rasterized layer } \description{ This geom is similar to \code{\link[ggplot2]{geom_jitter}}, but creates a raster layer } \section{Aesthetics}{ \code{geom_point()} understands the following aesthetics (required aesthetics are in bold): \itemize{ \item \strong{\code{x}} \item \strong{\code{y}} \item \code{alpha} \item \code{colour} \item \code{fill} \item \code{group} \item \code{shape} \item \code{size} \item \code{stroke} } Learn more about setting these aesthetics in \code{vignette("ggplot2-specs")}. } \examples{ library(ggplot2) library(ggrastr) ggplot(mpg) + geom_jitter_rast(aes(x = factor(cyl), y = hwy), raster.dpi = 600) } ggrastr/man/rasterise.Rd0000644000176200001440000000456114436024313014774 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/rasterise.R \name{rasterise} \alias{rasterise} \alias{rasterise.Layer} \alias{rasterise.list} \alias{rasterise.ggplot} \title{Rasterise ggplot layers Takes a ggplot object or a layer as input and renders their graphical output as a raster.} \usage{ rasterise(input, ...) \method{rasterise}{Layer}(input, ..., dpi = NULL, dev = "cairo", scale = 1) \method{rasterise}{list}(input, ..., dpi = NULL, dev = "cairo", scale = 1) \method{rasterise}{ggplot}( input, ..., layers = c("Point", "Tile"), dpi = NULL, dev = "cairo", scale = 1 ) } \arguments{ \item{input}{ggplot plot object to rasterize} \item{...}{ignored} \item{dpi}{integer Sets the desired resolution in dots per inch (default=NULL).} \item{dev}{string Specifies the device used, which can be one of: \code{"cairo"}, \code{"ragg"}, \code{"ragg_png"} or \code{"cairo_png"} (default="cairo").} \item{scale}{numeric Scaling factor to modify the raster object size (default=1). The parameter 'scale=1' results in an object size that is unchanged, 'scale'>1 increase the size, and 'scale'<1 decreases the size. These parameters are passed to 'height' and 'width' of grid::grid.raster(). Please refer to 'rasterise()' and 'grid::grid.raster()' for more details.} \item{layers}{list of layer types that should be rasterized} } \value{ A modified \code{Layer} object. } \description{ Rasterise ggplot layers Takes a ggplot object or a layer as input and renders their graphical output as a raster. } \details{ The default \code{dpi} (\code{NULL} (i.e. let the device decide)) can conveniently be controlled by setting the option \code{"ggrastr.default.dpi"} (e.g. \code{options("ggrastr.default.dpi" = 30)} for drafting). } \examples{ require(ggplot2) # `rasterise()` is used to wrap layers ggplot(pressure, aes(temperature, pressure)) + rasterise(geom_line()) # The `dpi` argument controls resolution ggplot(faithful, aes(eruptions, waiting)) + rasterise(geom_point(), dpi = 5) # The `dev` argument offers a few options for devices require(ragg) ggplot(diamonds, aes(carat, depth, z = price)) + rasterise(stat_summary_hex(), dev = "ragg") # The `scale` argument allows you to render a 'big' plot in small window, or vice versa. ggplot(faithful, aes(eruptions, waiting)) + rasterise(geom_point(), scale = 4) } \author{ Teun van den Brand } ggrastr/man/geom_quasirandom_rast.Rd0000644000176200001440000000574514436024313017363 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/geom-quasirandom-rast.R \name{geom_quasirandom_rast} \alias{geom_quasirandom_rast} \title{This geom is similar to \code{\link[ggbeeswarm]{geom_quasirandom}}, but creates a raster layer} \usage{ geom_quasirandom_rast( ..., width = NULL, varwidth = FALSE, bandwidth = 0.5, nbins = NULL, method = "quasirandom", groupOnX = NULL, dodge.width = 0, raster.dpi = getOption("ggrastr.default.dpi", 300), dev = "cairo", scale = 1 ) } \arguments{ \item{...}{Other arguments passed on to \code{\link[ggplot2:layer]{layer()}}. These are often aesthetics, used to set an aesthetic to a fixed value, like \code{colour = "red"} or \code{size = 3}. They may also be parameters to the paired geom/stat.} \item{width}{the maximum amount of spread (default: 0.4)} \item{varwidth}{vary the width by the relative size of each group} \item{bandwidth}{the bandwidth adjustment to use when calculating density Smaller numbers (< 1) produce a tighter "fit". (default: 0.5)} \item{nbins}{the number of bins used when calculating density (has little effect with quasirandom/random distribution)} \item{method}{the method used for distributing points (quasirandom, pseudorandom, smiley, maxout, frowney, minout, tukey, tukeyDense). See \code{\link[vipor:offsetX]{vipor::offsetSingleGroup()}} for the details of each method.} \item{groupOnX}{\ifelse{html}{\href{https://lifecycle.r-lib.org/articles/stages.html#deprecated}{\figure{lifecycle-deprecated.svg}{options: alt='[Deprecated]'}}}{\strong{[Deprecated]}} No longer needed.} \item{dodge.width}{Amount by which points from different aesthetic groups will be dodged. This requires that one of the aesthetics is a factor.} \item{raster.dpi}{integer Resolution of the rastered image in dots per inch (default=300).} \item{dev}{string Specifies the device used, which can be one of: \code{"cairo"}, \code{"ragg"} or \code{"ragg_png"} (default="cairo").} \item{scale}{numeric Scaling factor to modify the raster object size (default=1). The parameter 'scale=1' results in an object size that is unchanged, 'scale'>1 increase the size, and 'scale'<1 decreases the size. These parameters are passed to 'height' and 'width' of grid::grid.raster(). Please refer to 'rasterise()' and 'grid::grid.raster()' for more details.} } \value{ geom_quasirandom plot with rasterized layer } \description{ This geom is similar to \code{\link[ggbeeswarm]{geom_quasirandom}}, but creates a raster layer } \section{Aesthetics}{ \code{geom_point()} understands the following aesthetics (required aesthetics are in bold): \itemize{ \item \strong{\code{x}} \item \strong{\code{y}} \item \code{alpha} \item \code{colour} \item \code{fill} \item \code{group} \item \code{shape} \item \code{size} \item \code{stroke} } Learn more about setting these aesthetics in \code{vignette("ggplot2-specs")}. } \examples{ library(ggplot2) library(ggrastr) ggplot(mtcars) + geom_quasirandom_rast(aes(x = factor(cyl), y = mpg), raster.dpi = 600) } ggrastr/man/geom_point_rast.Rd0000644000176200001440000000353614436024313016165 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/geom-point-rast.R \name{geom_point_rast} \alias{geom_point_rast} \title{This geom is similar to \code{\link[ggplot2]{geom_point}}, but creates a raster layer} \usage{ geom_point_rast( ..., raster.dpi = getOption("ggrastr.default.dpi", 300), dev = "cairo", scale = 1 ) } \arguments{ \item{...}{Other arguments passed on to \code{\link[ggplot2:layer]{layer()}}. These are often aesthetics, used to set an aesthetic to a fixed value, like \code{colour = "red"} or \code{size = 3}. They may also be parameters to the paired geom/stat.} \item{raster.dpi}{integer Resolution of the rastered image in dots per inch (default=300).} \item{dev}{string Specifies the device used, which can be one of: \code{"cairo"}, \code{"ragg"} or \code{"ragg_png"} (default="cairo").} \item{scale}{numeric Scaling factor to modify the raster object size (default=1). The parameter 'scale=1' results in an object size that is unchanged, 'scale'>1 increase the size, and 'scale'<1 decreases the size. These parameters are passed to 'height' and 'width' of grid::grid.raster(). Please refer to 'rasterise()' and 'grid::grid.raster()' for more details.} } \value{ geom_point plot with rasterized layer } \description{ This geom is similar to \code{\link[ggplot2]{geom_point}}, but creates a raster layer } \section{Aesthetics}{ \code{geom_point()} understands the following aesthetics (required aesthetics are in bold): \itemize{ \item \strong{\code{x}} \item \strong{\code{y}} \item \code{alpha} \item \code{colour} \item \code{fill} \item \code{group} \item \code{shape} \item \code{size} \item \code{stroke} } Learn more about setting these aesthetics in \code{vignette("ggplot2-specs")}. } \examples{ library(ggplot2) library(ggrastr) ggplot() + geom_point_rast(aes(x=rnorm(1000), y=rnorm(1000)), raster.dpi=600) } ggrastr/man/geom_violin_rast.Rd0000644000176200001440000000356514436024313016336 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/geom-violin-rast.R \name{geom_violin_rast} \alias{geom_violin_rast} \title{This geom is similar to \code{\link[ggplot2]{geom_violin}}, but creates a raster layer} \usage{ geom_violin_rast( ..., raster.dpi = getOption("ggrastr.default.dpi", 300), dev = "cairo", scale = 1 ) } \arguments{ \item{...}{Other arguments passed on to \code{\link[ggplot2:layer]{layer()}}. These are often aesthetics, used to set an aesthetic to a fixed value, like \code{colour = "red"} or \code{size = 3}. They may also be parameters to the paired geom/stat.} \item{raster.dpi}{integer Resolution of the rastered image in dots per inch (default=300).} \item{dev}{string Specifies the device used, which can be one of: \code{"cairo"}, \code{"ragg"} or \code{"ragg_png"} (default="cairo").} \item{scale}{numeric Scaling factor to modify the raster object size (default=1). The parameter 'scale=1' results in an object size that is unchanged, 'scale'>1 increase the size, and 'scale'<1 decreases the size. These parameters are passed to 'height' and 'width' of grid::grid.raster(). Please refer to 'rasterise()' and 'grid::grid.raster()' for more details.} } \value{ geom_violin_rast plot with rasterized layer } \description{ This geom is similar to \code{\link[ggplot2]{geom_violin}}, but creates a raster layer } \section{Aesthetics}{ \code{geom_violin()} understands the following aesthetics (required aesthetics are in bold): \itemize{ \item \strong{\code{x}} \item \strong{\code{y}} \item \code{alpha} \item \code{colour} \item \code{fill} \item \code{group} \item \code{linetype} \item \code{linewidth} \item \code{weight} } Learn more about setting these aesthetics in \code{vignette("ggplot2-specs")}. } \examples{ library(ggplot2) library(ggrastr) ggplot(mpg) + geom_violin_rast(aes(x = factor(cyl), y = hwy), raster.dpi = 600) } ggrastr/man/rasterize.Rd0000644000176200001440000000257314436024313015004 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/rasterise.R \name{rasterize} \alias{rasterize} \title{Rasterise ggplot layers Takes a ggplot object or a layer as input and renders their graphical output as a raster.} \usage{ rasterize(input, ...) } \arguments{ \item{input}{ggplot plot object to rasterize} \item{...}{ignored} } \value{ A modified \code{Layer} object. } \description{ Rasterise ggplot layers Takes a ggplot object or a layer as input and renders their graphical output as a raster. } \details{ The default \code{dpi} (\code{NULL} (i.e. let the device decide)) can conveniently be controlled by setting the option \code{"ggrastr.default.dpi"} (e.g. \code{options("ggrastr.default.dpi" = 30)} for drafting). } \examples{ require(ggplot2) # `rasterise()` is used to wrap layers ggplot(pressure, aes(temperature, pressure)) + rasterise(geom_line()) # The `dpi` argument controls resolution ggplot(faithful, aes(eruptions, waiting)) + rasterise(geom_point(), dpi = 5) # The `dev` argument offers a few options for devices require(ragg) ggplot(diamonds, aes(carat, depth, z = price)) + rasterise(stat_summary_hex(), dev = "ragg") # The `scale` argument allows you to render a 'big' plot in small window, or vice versa. ggplot(faithful, aes(eruptions, waiting)) + rasterise(geom_point(), scale = 4) } \author{ Teun van den Brand } ggrastr/man/theme_pdf.Rd0000644000176200001440000000117414436024313014723 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/utils.R \name{theme_pdf} \alias{theme_pdf} \title{Pretty theme} \usage{ theme_pdf(show.ticks = TRUE, legend.pos = NULL) } \arguments{ \item{show.ticks}{boolean Whether to show x- and y-ticks (default=TRUE).} \item{legend.pos}{Vector with x and y position of the legend (default=NULL).} } \value{ ggplot2 with plot ticks and positioned legend } \description{ Pretty theme } \examples{ library(ggplot2) library(ggrastr) data = rnorm(100) colors = (1:100/100) ggplot() + geom_point(aes(x=data, y=data, color=colors)) + theme_pdf(FALSE, legend.pos=c(1, 1)) } ggrastr/man/geom_boxplot_jitter.Rd0000644000176200001440000001206414436024313017047 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/geom-boxplot-jitter.R \name{geom_boxplot_jitter} \alias{geom_boxplot_jitter} \title{This geom is similar to \code{\link[ggplot2]{geom_boxplot}}, but allows to jitter outlier points and to raster points layer.} \usage{ geom_boxplot_jitter( mapping = NULL, data = NULL, dev = "cairo", stat = "boxplot", position = "dodge", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ..., outlier.jitter.width = NULL, outlier.jitter.height = 0, raster.dpi = getOption("ggrastr.default.dpi", 300), scale = 1 ) } \arguments{ \item{mapping}{Set of aesthetic mappings created by \code{\link[ggplot2:aes]{aes()}}. If specified and \code{inherit.aes = TRUE} (the default), it is combined with the default mapping at the top level of the plot. You must supply \code{mapping} if there is no plot mapping.} \item{data}{The data to be displayed in this layer. There are three options: If \code{NULL}, the default, the data is inherited from the plot data as specified in the call to \code{\link[ggplot2:ggplot]{ggplot()}}. A \code{data.frame}, or other object, will override the plot data. All objects will be fortified to produce a data frame. See \code{\link[ggplot2:fortify]{fortify()}} for which variables will be created. A \code{function} will be called with a single argument, the plot data. The return value must be a \code{data.frame}, and will be used as the layer data. A \code{function} can be created from a \code{formula} (e.g. \code{~ head(.x, 10)}).} \item{dev}{string Specifies the device used, which can be one of: \code{"cairo"}, \code{"ragg"} or \code{"ragg_png"} (default="cairo").} \item{stat}{string The statistical transformation to use on the data for this layer, either as a ggproto Geom subclass or as a string naming the stat stripped of the stat_ prefix (e.g. "count" rather than "stat_count"). Refer to ggplot2::layer.} \item{position}{Position adjustment, either as a string naming the adjustment (e.g. \code{"jitter"} to use \code{position_jitter}), or the result of a call to a position adjustment function. Use the latter if you need to change the settings of the adjustment.} \item{na.rm}{If \code{FALSE}, the default, missing values are removed with a warning. If \code{TRUE}, missing values are silently removed.} \item{show.legend}{logical. Should this layer be included in the legends? \code{NA}, the default, includes if any aesthetics are mapped. \code{FALSE} never includes, and \code{TRUE} always includes. It can also be a named logical vector to finely select the aesthetics to display.} \item{inherit.aes}{If \code{FALSE}, overrides the default aesthetics, rather than combining with them. This is most useful for helper functions that define both data and aesthetics and shouldn't inherit behaviour from the default plot specification, e.g. \code{\link[ggplot2:borders]{borders()}}.} \item{...}{Other arguments passed on to \code{\link[ggplot2:layer]{layer()}}. These are often aesthetics, used to set an aesthetic to a fixed value, like \code{colour = "red"} or \code{size = 3}. They may also be parameters to the paired geom/stat.} \item{outlier.jitter.width}{numeric Amount of horizontal jitter (default=NULL). The jitter is added in both positive and negative directions, so the total spread is twice the value specified here. If NULL, no jitter performed.} \item{outlier.jitter.height}{numeric Amount of horizontal jitter (default=0). The jitter is added in both positive and negative directions, so the total spread is twice the value specified here.} \item{raster.dpi}{integer Resolution of the rastered image (default=300). Ignored if \code{raster == FALSE}.} \item{scale}{numeric Scaling factor to modify the raster object size (default=1). The parameter 'scale=1' results in an object size that is unchanged, 'scale'>1 increase the size, and 'scale'<1 decreases the size. These parameters are passed to 'height' and 'width' of grid::grid.raster(). Please refer to 'rasterise()' and 'grid::grid.raster()' for more details.} } \value{ geom_boxplot plot with rasterized layer } \description{ This geom is similar to \code{\link[ggplot2]{geom_boxplot}}, but allows to jitter outlier points and to raster points layer. } \section{Aesthetics}{ \code{geom_boxplot()} understands the following aesthetics (required aesthetics are in bold): \itemize{ \item \strong{\code{x} \emph{or} \code{y}} \item \strong{\code{lower} \emph{or} \code{xlower}} \item \strong{\code{upper} \emph{or} \code{xupper}} \item \strong{\code{middle} \emph{or} \code{xmiddle}} \item \strong{\code{ymin} \emph{or} \code{xmin}} \item \strong{\code{ymax} \emph{or} \code{xmax}} \item \code{alpha} \item \code{colour} \item \code{fill} \item \code{group} \item \code{linetype} \item \code{linewidth} \item \code{shape} \item \code{size} \item \code{weight} } Learn more about setting these aesthetics in \code{vignette("ggplot2-specs")}. } \examples{ library(ggplot2) library(ggrastr) yvalues = rt(1000, df=3) xvalues = as.factor(1:1000 \%\% 2) ggplot() + geom_boxplot_jitter(aes(y=yvalues, x=xvalues), outlier.jitter.width = 0.1, raster = TRUE) } ggrastr/man/geom_beeswarm_rast.Rd0000644000176200001440000000460414436024313016636 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/geom-beeswarm-rast.R \name{geom_beeswarm_rast} \alias{geom_beeswarm_rast} \title{This geom is similar to \code{\link[ggbeeswarm]{geom_beeswarm}}, but creates a raster layer} \usage{ geom_beeswarm_rast( ..., priority = c("ascending", "descending", "density", "random", "none"), cex = 1, groupOnX = NULL, dodge.width = 0, raster.dpi = getOption("ggrastr.default.dpi", 300), dev = "cairo", scale = 1 ) } \arguments{ \item{...}{Other arguments passed on to \code{\link[ggplot2:layer]{layer()}}. These are often aesthetics, used to set an aesthetic to a fixed value, like \code{colour = "red"} or \code{size = 3}. They may also be parameters to the paired geom/stat.} \item{priority}{string Method used to perform point layout (see ggbeeswarm::position_beeswarm).} \item{cex}{numeric Scaling for adjusting point spacing (see ggbeeswarm::position_beeswarm)} \item{groupOnX}{boolean Whether jitter be added to the x axis (default=NULL). if TRUE then jitter is added to the x axis and if FALSE jitter is added to the y axis. (The default NULL causes the function to guess which axis is the categorical axis based on the number of unique entries in each). Refer to see ggbeeswarm::position_beeswarm for more details.} \item{dodge.width}{numeric Amount by which points from different aesthetic groups will be dodged (default=0). This requires that one of the aesthetics is a factor. Refer to see ggbeeswarm::position_beeswarm for more details.} \item{raster.dpi}{integer Resolution of the rastered image in dots per inch (default=300).} \item{dev}{string Specifies the device used, which can be one of: \code{"cairo"}, \code{"ragg"} or \code{"ragg_png"} (default="cairo").} \item{scale}{numeric Scaling factor to modify the raster object size (default=1). The parameter 'scale=1' results in an object size that is unchanged, 'scale'>1 increase the size, and 'scale'<1 decreases the size. These parameters are passed to 'height' and 'width' of grid::grid.raster(). Please refer to 'rasterise()' and 'grid::grid.raster()' for more details.} } \value{ geom_beeswarm plot with rasterized layer } \description{ This geom is similar to \code{\link[ggbeeswarm]{geom_beeswarm}}, but creates a raster layer } \examples{ library(ggplot2) library(ggrastr) ggplot(mtcars) + geom_beeswarm_rast(aes(x = factor(cyl), y = mpg), raster.dpi = 600, cex = 1.5) } ggrastr/man/geom_tile_rast.Rd0000644000176200001440000000403014436024313015757 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/geom-tile-rast.R \name{geom_tile_rast} \alias{geom_tile_rast} \title{This geom is similar to \code{\link[ggplot2]{geom_tile}}, but creates a raster layer} \usage{ geom_tile_rast( ..., raster.dpi = getOption("ggrastr.default.dpi", 300), dev = "cairo", scale = 1 ) } \arguments{ \item{...}{Other arguments passed on to \code{\link[ggplot2:layer]{layer()}}. These are often aesthetics, used to set an aesthetic to a fixed value, like \code{colour = "red"} or \code{size = 3}. They may also be parameters to the paired geom/stat.} \item{raster.dpi}{integer Resolution of the rastered image in dots per inch (default=300).} \item{dev}{string Specifies the device used, which can be one of: \code{"cairo"}, \code{"ragg"} or \code{"ragg_png"} (default="cairo").} \item{scale}{numeric Scaling factor to modify the raster object size (default=1). The parameter 'scale=1' results in an object size that is unchanged, 'scale'>1 increase the size, and 'scale'<1 decreases the size. These parameters are passed to 'height' and 'width' of grid::grid.raster(). Please refer to 'rasterise()' and 'grid::grid.raster()' for more details.} } \value{ geom_tile plot with rasterized layer } \description{ This geom is similar to \code{\link[ggplot2]{geom_tile}}, but creates a raster layer } \section{Aesthetics}{ \code{geom_tile()} understands the following aesthetics (required aesthetics are in bold): \itemize{ \item \strong{\code{x}} \item \strong{\code{y}} \item \code{alpha} \item \code{colour} \item \code{fill} \item \code{group} \item \code{height} \item \code{linetype} \item \code{linewidth} \item \code{width} } Note that \code{geom_raster()} ignores \code{colour}. Learn more about setting these aesthetics in \code{vignette("ggplot2-specs")}. } \examples{ library(ggplot2) library(ggrastr) coords <- expand.grid(1:100, 1:100) coords$Value <- 1 / apply(as.matrix(coords), 1, function(x) sum((x - c(50, 50))^2)^0.01) ggplot(coords) + geom_tile_rast(aes(x=Var1, y=Var2, fill=Value)) } ggrastr/DESCRIPTION0000644000176200001440000000231614436033072013435 0ustar liggesusersPackage: ggrastr Type: Package Title: Rasterize Layers for 'ggplot2' Version: 1.0.2 Authors@R: c(person("Viktor", "Petukhov", email = "viktor.s.petukhov@ya.ru", role = c("aut", "cph")), person("Teun", "van den Brand", email = "t.vd.brand@nki.nl", role=c("aut")), person("Evan", "Biederstedt", email = "evan.biederstedt@gmail.com", role=c("cre", "aut"))) Description: Rasterize only specific layers of a 'ggplot2' plot while simultaneously keeping all labels and text in vector format. This allows users to keep plots within the reasonable size limit without loosing vector properties of the scale-sensitive information. License: MIT + file LICENSE Encoding: UTF-8 Imports: ggplot2 (>= 2.1.0), Cairo (>= 1.5.9), ggbeeswarm, grid, png, ragg Depends: R (>= 3.2.2) RoxygenNote: 7.2.3 Suggests: knitr, maps, rmarkdown, sf VignetteBuilder: knitr URL: https://github.com/VPetukhov/ggrastr BugReports: https://github.com/VPetukhov/ggrastr/issues NeedsCompilation: no Author: Viktor Petukhov [aut, cph], Teun van den Brand [aut], Evan Biederstedt [cre, aut] Maintainer: Evan Biederstedt Packaged: 2023-06-01 05:31:06 UTC; evanbiederstedt Repository: CRAN Date/Publication: 2023-06-01 06:10:02 UTC ggrastr/build/0000755000176200001440000000000014436026432013026 5ustar liggesusersggrastr/build/vignette.rds0000644000176200001440000000037114436026432015366 0ustar liggesusersuQ=0-v]ECH'%SZc!޽w=!bML9"- D̲PrG ܏5kWYp㔜9p;N0ޘlm4T[!t]29"֓n1CNf4B= Z8pŷ0۝L 姿P`qECJW-=0TUl: Z(G PQgggrastr/vignettes/0000755000176200001440000000000014436026432013737 5ustar liggesusersggrastr/vignettes/Raster_geoms.Rmd0000644000176200001440000001521014436002437017033 0ustar liggesusers--- title: "ggrastr" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{ggrastr} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` # ggrastr ## Rasterizing ggplot objects with `rasterize` When you need to plot data with many observations, storing plots completely in vector format is unsuitable: it requires tons of space and is very slow to work with in graphic editors. On the other hand, completely rasterizing the plot distorts important text content and prevents readers from editing and copying. The solution provided here within the package `ggrastr` is to rasterize layers that have a lot of data points, keeping all the rest in vector format. The simplest way to rasterize some of your layers is to call `rasterize` on the plot object: ```{r, fig.width=5, fig.height=5} library(ggplot2) library(ggrastr) plot <- ggplot(diamonds, aes(carat, price, colour = cut)) + geom_point() rasterize(plot, layers='Point', dpi=50) ``` The layer parameter here accepts the layers, which should be rasterized and can work with vectors of layer types. ## Rasterizing individual layers The same function can be applied on the level of individual layers. It allows users to rasterize only some layers of the same type: ```{r, fig.width=5, fig.height=5} ggplot() + rasterise(geom_point(aes(carat, price, colour = cut), data=diamonds), dpi=30) + geom_point(aes(x=runif(20, 0, 5), y=runif(20, 0, 20000)), size=10, color="black", shape=8) ``` Note that when the aspect ratio is distorted, the objects are rendered without distortion, i.e. the points in this example are still circles: ```{r, fig.width=5, fig.height=5} # Points remain round across different aspect ratios plot <- ggplot(diamonds, aes(carat, price, colour = cut)) plot + rasterise(geom_point(), dpi = 72) + theme(aspect.ratio = 0.2) ``` ## Advanced options ### Selecting rendering device By default, plots are rendered with [Cairo](https://CRAN.R-project.org/package=Cairo). However, users now have the option to render plots with the [ragg](https://github.com/r-lib/ragg) device. The motivation for using `ragg` is that `ragg` can be faster and has better anti-aliasing. That being said, the default ragg device also has some alpha blending quirks. Because of these quirks, users are recommended to use the `ragg_png` option to work around the alpha blending. The differences in devices are best seen at lower resolution: ```{r, fig.width=5, fig.height=5} # The default 'cairo' at dpi=5 plot + rasterise(geom_point(), dpi = 5, dev = "cairo") ``` ```{r, fig.width=5, fig.height=5} # Using 'ragg' gives better anti-aliasing but has unexpected alpha blending plot + rasterise(geom_point(), dpi = 5, dev = "ragg") ``` ```{r, fig.width=5, fig.height=5} # Using 'ragg_png' solves the alpha blend, but requires writing a temporary file to disk plot + rasterise(geom_point(), dpi = 5, dev = "ragg_png") ``` Note that facets are rendered correctly without users having to adjust the width/height settings. ```{r, fig.width=5, fig.height=5} # Facets will not warp/distort points set.seed(123) plot + rasterise(geom_point(), dpi = 300) + facet_wrap(~ sample(1:3, nrow(diamonds), 2)) ``` ### Scaling size of raster objects Users are also able to change the size of the raster objects with the parameter `scale`. The default behavior is not to modify the size with `scale=1`: ```{r, fig.width=5, fig.height=5} # unchanged scaling, scale=1 plot <- ggplot(diamonds, aes(carat, price, colour = cut)) plot + rasterise(geom_point(), dpi = 300, scale = 1) ``` Setting `scale` to values greater than 1 will increase the size of the rasterized objects. In this case, `scale=2` will double the size of the points in comparison to the original plot: ```{r, fig.width=5, fig.height=5} # larger objects, scale > 1 plot <- ggplot(diamonds, aes(carat, price, colour = cut)) plot + rasterise(geom_point(), dpi = 300, scale = 2) ``` Similarly, values less than 1 will result in smaller objects. Here we see `scale=0.5` results in points half the size of the points in the original plot above: ```{r, fig.width=5, fig.height=5} # smaller objects, scale < 1 plot <- ggplot(diamonds, aes(carat, price, colour = cut)) plot + rasterise(geom_point(), dpi = 300, scale = 0.5) ``` ### Rasterize multiple layers with lists As of ggrastr versions `>=0.2.3`, users are also able to rasterize multiple layers at once using (valid) lists. It is mainly useful when working with `geom_sf`, as it returns the list object instead of a single geom: ```{r, fig.width=7, fig.height=5} world1 <- sf::st_as_sf(maps::map('world', plot = FALSE, fill = TRUE)) ggplot() + rasterise( list( list( geom_sf(data = world1), theme(panel.background = element_rect(fill = "skyblue")) ), list( list( geom_point(aes(x = rnorm(100, sd = 10), y = rnorm(100, sd = 10))) ), theme(panel.border = element_rect(fill = NA, colour = "blue")) ) ) ) ``` ### Set the parameter 'dpi' globally with options(ggrastr.default.dpi=N) The parameter `dpi` is an integer which sets the desired resolution in dots per inch. With ggrastr versions `>=0.2.2`, users can set this parameter globally, using [options()](https://stat.ethz.ch/R-manual/R-devel/library/base/html/options.html). In the following example, plots will be rendered with `dpi=750` after the user sets this with `options(ggrastr.default.dpi=750)`: ```{r, fig.width=5, fig.height=5} ## set ggrastr.default.dpi with options() options(ggrastr.default.dpi=750) plot <- ggplot(diamonds, aes(carat, price, colour = cut)) new_plot = plot + rasterise(geom_point()) + theme(aspect.ratio = 1) print(new_plot) ## set back to default 300 options(ggrastr.default.dpi=300) ``` ## Other wrapper functions For legacy reasons, we have all popular geoms wrapped inside the package. However, we strongly encourage users to use the `rasterise()` function instead. * `geom_point_rast`: raster scatter plots * `geom_jitter_rast`: raster jittered scatter plots * `geom_boxplot_jitter`: boxplots that allows to jitter and rasterize outlier points * `geom_tile_rast`: raster heatmap * `geom_beeswarm_rast`: raster [bee swarm plots](https://github.com/eclarke/ggbeeswarm#geom_beeswarm) * `geom_quasirandom_rast`: raster [quasirandom scatter plot](https://github.com/eclarke/ggbeeswarm#geom_quasirandom) For more details, see the vignettes detailing these legacy functions [here](https://github.com/VPetukhov/ggrastr/blob/main/vignettes/Legacy_functions.md) (for the Markdown version) and [here](https://htmlpreview.github.io/?https://raw.githubusercontent.com/VPetukhov/ggrastr/main/doc/Legacy_functions.html) (for the HTML version). ggrastr/vignettes/Legacy_functions.Rmd0000644000176200001440000002063514436002437017704 0ustar liggesusers--- title: "Legacy (outdated) wrapper functions" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Legacy (outdated) wrapper functions} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` # Legacy (outdated) wrapper functions For historic reasons, `ggrastr` used to be solely composed of the following functions: * `geom_point_rast`: raster scatter plots * `geom_jitter_rast`: raster jittered scatter plots * `geom_boxplot_jitter`: boxplots that allows to jitter and rasterize outlier points * `geom_tile_rast`: raster heatmap * `geom_beeswarm_rast`: raster [bee swarm plots](https://github.com/eclarke/ggbeeswarm#geom_beeswarm) * `geom_quasirandom_rast`: raster [quasirandom scatter plot](https://github.com/eclarke/ggbeeswarm#geom_quasirandom) However, we strongly encourage users to use the `rasterise()` function instead. For posterity's sake, we have only included the old vignettes here for the reference of users, along with the equivalent functions using `rasterise()`. #### Points: Rasterize scatter plots with geom_point_rast() Sometimes you need to publish a figure in a vector format: ```{r, fig.width=5, fig.height=5} library(ggplot2) library(ggrastr) points_num <- 10000 df <- data.frame(x=rnorm(points_num), y=rnorm(points_num), c=as.factor(1:points_num %% 2)) gg <- ggplot(df, aes(x=x, y=y, color=c)) + scale_color_discrete(guide="none") gg_vec <- gg + geom_point(size=0.5) print(gg_vec) ``` But in other cases, your figure contains thousands of points, e.g. try `points_num <- 500000` in the example above, and you will notice the performance issues---it takes significantly longer to render the plot. In this case, a reasonable solution would be to rasterize the plot. But the problem is that all text becomes rasterized as well. Raster layers with `ggrastr` were developed to prevent such a situation, using `rasterized ```{r, fig.width=5, fig.height=5} gg_rasterized <- gg + rasterise(geom_point(), dpi = 300, scale = 1) print(gg_rasterized) ``` The legacy function used in older versions of ggrastr was `geom_point_rast()`: ```{r, fig.width=5, fig.height=5} gg_rast <- gg + geom_point_rast(size=0.5) print(gg_rast) ``` The plots look the same, but the difference in size can be seen when they are exported to pdfs. Unfortunately, there is a longer rendering time to produce such plots: ```{r} PrintFileSize <- function(gg, name) { invisible(ggsave('tmp.pdf', gg, width=4, height=4)) cat(name, ': ', file.info('tmp.pdf')$size / 1024, ' Kb.\n', sep = '') unlink('tmp.pdf') } PrintFileSize(gg_rast, 'Raster') PrintFileSize(gg_vec, 'Vector') ``` As expected, the difference becomes larger with growth of number of points: ```{r} points_num <- 1000000 df <- data.frame(x=rnorm(points_num), y=rnorm(points_num), c=as.factor(1:points_num %% 2)) gg <- ggplot(df, aes(x=x, y=y, color=c)) + scale_color_discrete(guide="none") gg_vec <- gg + geom_point(size=0.5) gg_rast <- gg + geom_point_rast(size=0.5) PrintFileSize(gg_rast, 'Raster') PrintFileSize(gg_vec, 'Vector') ``` #### Jitter: Rasterize jittered scatter plots with geom_jitter_rast() Users may also opt to create rasterized scatter plots with jitter: ```{r, fig.width=5, fig.height=5} library(ggplot2) library(ggrastr) points_num <- 5000 df <- data.frame(x=rnorm(points_num), y=rnorm(points_num), c=as.factor(1:points_num %% 2)) gg <- ggplot(df, aes(x=x, y=y, color=c)) + scale_color_discrete(guide="none") gg_jitter_rast <- gg + rasterise(geom_jitter(), dpi = 300, scale = 1) print(gg_jitter_rast) ``` The legacy wrapper `geom_jitter_rast()` used the following syntax: ```{r, fig.width=5, fig.height=5} library(ggplot2) library(ggrastr) points_num <- 5000 df <- data.frame(x=rnorm(points_num), y=rnorm(points_num), c=as.factor(1:points_num %% 2)) gg <- ggplot(df, aes(x=x, y=y, color=c)) + scale_color_discrete(guide=FALSE) gg_jitter_rast <- gg + geom_jitter_rast(raster.dpi=600) print(gg_jitter_rast) ``` #### Tiles: Rasterize heatmaps with geom_tile_rast() Heatmaps also have similar issues with the default vectorized formats: ```{r, fig.width=5, fig.height=5} library(ggplot2) library(ggrastr) coords <- expand.grid(1:500, 1:500) coords$Value <- 1 / apply(as.matrix(coords), 1, function(x) sum((x - c(50, 50))^2)^0.01) gg_tile_vec <- ggplot(coords) + geom_tile(aes(x=Var1, y=Var2, fill=Value)) gg_tile_rast <- ggplot(coords) + rasterise(geom_tile(aes(x=Var1, y=Var2, fill=Value)), dpi = 300, scale = 1) print(gg_tile_rast) ``` The legacy function `geom_tile_rast()` used the following syntax: ```{r, fig.width=5, fig.height=5} gg_tile_rast <- ggplot(coords) + geom_tile_rast(aes(x=Var1, y=Var2, fill=Value)) print(gg_tile_rast) ``` Note that we can see that the rasterized plots using `ggrastr` are lighter in size when rendered to pdf: ```{r} PrintFileSize(gg_tile_rast, 'Raster') PrintFileSize(gg_tile_vec, 'Vector') ``` #### Violin plots: Rasterize violin plots with geom_violin_rast() One can see a similar effect with violin plots: ```{r, fig.width=5, fig.height=5} library(ggplot2) library(ggrastr) gg_violin_vec <- ggplot(mtcars, aes(factor(cyl), mpg)) + geom_violin() gg_violin_rast <- ggplot(mtcars) + rasterise(geom_violin(aes(factor(cyl), mpg))) print(gg_violin_rast) ``` The legacy function `geom_violin_rast()` had the following syntax: ```{r, fig.width=5, fig.height=5} gg_violin_rast <- ggplot(mtcars) + geom_violin_rast(aes(factor(cyl), mpg)) print(gg_violin_rast) ``` ```{r} ## difference in size shown PrintFileSize(gg_tile_rast, 'Raster') PrintFileSize(gg_tile_vec, 'Vector') ``` #### Box plots: Jitter outliers and rasterize box plots with geom_boxplot_jitter Another type of plot with a potentially large number of small objects is geom_boxplot: ```{r, fig.width=5, fig.height=5} library(ggplot2) library(ggrastr) points_num <- 5000 df <- data.frame(x=as.factor(1:points_num %% 2), y=log(abs(rcauchy(points_num)))) gg <- ggplot(df, aes(x=x, y=y)) + scale_color_discrete(guide="none") boxplot <- gg + geom_boxplot() print(boxplot) ``` With a large number of objects, outlier points become noninformative. For example, here is the rendered plot with `points_num <- 1000000`. For such a large number of points, it would be better to jitter them using `geom_boxplot_jitter()`: ```{r, fig.width=5, fig.height=5} library(ggplot2) library(ggrastr) points_num <- 500000 df <- data.frame(x=as.factor(1:points_num %% 2), y=log(abs(rcauchy(points_num)))) gg <- ggplot(df, aes(x=x, y=y)) + scale_color_discrete(guide="none") gg_box_vec <- gg + geom_boxplot_jitter(outlier.size=0.1, outlier.jitter.width=0.3, outlier.alpha=0.5) print(gg_box_vec) ``` And this geom can be rasterized as well: ```{r, fig.width=5, fig.height=5} gg_box_rast <- gg + geom_boxplot_jitter(outlier.size=0.1, outlier.jitter.width=0.3, outlier.alpha=0.5, raster.dpi=200) print(gg_box_rast) ``` ```{r} PrintFileSize(gg_box_rast, 'Raster') PrintFileSize(gg_box_vec, 'Vector') ``` #### Beeswarm-style plots: geom_beeswarm_rast and geom_quasirandom ggrastr also allows users to create rasterized beeswarm plots. As described in the README for [ggbeeswarm](https://github.com/eclarke/ggbeeswarm), > Beeswarm plots (aka column scatter plots or violin scatter plots) are a way of plotting points that would ordinarily overlap so that they fall next to each other instead. In addition to reducing overplotting, it helps visualize the density of the data at each point (similar to a violin plot), while still showing each data point individually. The ggrastr geom `geom_beeswarm_rast` is similar to `ggbeeswarm::geom_beeswarm()`, but it provides a rasterized layer: ```{r, fig.width=5, fig.height=5} library(ggplot2) library(ggrastr) ggplot(mtcars) + geom_beeswarm_rast(aes(x = factor(cyl), y=mpg), raster.dpi=600, cex=1.5) ``` Again, we strongly encourage users to simply use `rasterise()`: ```{r, fig.width=5, fig.height=5} library(ggplot2) library(ggrastr) library(ggbeeswarm,) ggplot(mtcars) + rasterise(geom_beeswarm(aes(x = factor(cyl), y=mpg))) ``` Analogously, the legacy wrapper `geom_quasirandom_rast()` is much like `ggbeeswarm::geom_quasirandom()`, but with a rasterized layer: ```{r, fig.width=5, fig.height=5} library(ggplot2) library(ggrastr) ggplot(mtcars) + geom_quasirandom_rast(aes(x = factor(cyl), y=mpg), raster.dpi=600) ``` We encourage users to visit both [CRAN](https://CRAN.R-project.org/package=ggbeeswarm) and the [GitHub repo for ggbeeswam](https://github.com/eclarke/ggbeeswarm) for more details. ggrastr/vignettes/Legacy_functions.md0000644000176200001440000002251414436002437017560 0ustar liggesusers# Legacy (outdated) wrapper functions For historic reasons, `ggrastr` used to be solely composed of the following functions: - `geom_point_rast`: raster scatter plots - `geom_jitter_rast`: raster jittered scatter plots - `geom_boxplot_jitter`: boxplots that allows to jitter and rasterize outlier points - `geom_tile_rast`: raster heatmap - `geom_beeswarm_rast`: raster [bee swarm plots](https://github.com/eclarke/ggbeeswarm#geom_beeswarm) - `geom_quasirandom_rast`: raster [quasirandom scatter plot](https://github.com/eclarke/ggbeeswarm#geom_quasirandom) However, we strongly encourage users to use the `rasterise()` function instead. For posterity’s sake, we have only included the old vignettes here for the reference of users, along with the equivalent functions using `rasterise()`. #### Points: Rasterize scatter plots with geom\_point\_rast() Sometimes you need to publish a figure in a vector format: library(ggplot2) library(ggrastr) points_num <- 10000 df <- data.frame(x=rnorm(points_num), y=rnorm(points_num), c=as.factor(1:points_num %% 2)) gg <- ggplot(df, aes(x=x, y=y, color=c)) + scale_color_discrete(guide="none") gg_vec <- gg + geom_point(size=0.5) print(gg_vec) ![](Legacy_functions_files/figure-markdown_strict/unnamed-chunk-1-1.png) But in other cases, your figure contains thousands of points, e.g. try `points_num <- 500000` in the example above, and you will notice the performance issues—it takes significantly longer to render the plot. In this case, a reasonable solution would be to rasterize the plot. But the problem is that all text becomes rasterized as well. Raster layers with `ggrastr` were developed to prevent such a situation, using \`rasterized gg_rasterized <- gg + rasterise(geom_point(), dpi = 300, scale = 1) print(gg_rasterized) ![](Legacy_functions_files/figure-markdown_strict/unnamed-chunk-2-1.png) The legacy function used in older versions of ggrastr was `geom_point_rast()`: gg_rast <- gg + geom_point_rast(size=0.5) print(gg_rast) ![](Legacy_functions_files/figure-markdown_strict/unnamed-chunk-3-1.png) The plots look the same, but the difference in size can be seen when they are exported to pdfs. Unfortunately, there is a longer rendering time to produce such plots: PrintFileSize <- function(gg, name) { invisible(ggsave('tmp.pdf', gg, width=4, height=4)) cat(name, ': ', file.info('tmp.pdf')$size / 1024, ' Kb.\n', sep = '') unlink('tmp.pdf') } PrintFileSize(gg_rast, 'Raster') #> Raster: 327.1904 Kb. PrintFileSize(gg_vec, 'Vector') #> Vector: 557.2764 Kb. As expected, the difference becomes larger with growth of number of points: points_num <- 1000000 df <- data.frame(x=rnorm(points_num), y=rnorm(points_num), c=as.factor(1:points_num %% 2)) gg <- ggplot(df, aes(x=x, y=y, color=c)) + scale_color_discrete(guide="none") gg_vec <- gg + geom_point(size=0.5) gg_rast <- gg + geom_point_rast(size=0.5) PrintFileSize(gg_rast, 'Raster') #> Raster: 361.4082 Kb. PrintFileSize(gg_vec, 'Vector') #> Vector: 54818.25 Kb. #### Jitter: Rasterize jittered scatter plots with geom\_jitter\_rast() Users may also opt to create rasterized scatter plots with jitter: library(ggplot2) library(ggrastr) points_num <- 5000 df <- data.frame(x=rnorm(points_num), y=rnorm(points_num), c=as.factor(1:points_num %% 2)) gg <- ggplot(df, aes(x=x, y=y, color=c)) + scale_color_discrete(guide="none") gg_jitter_rast <- gg + rasterise(geom_jitter(), dpi = 300, scale = 1) print(gg_jitter_rast) ![](Legacy_functions_files/figure-markdown_strict/unnamed-chunk-6-1.png) The legacy wrapper `geom_jitter_rast()` used the following syntax: library(ggplot2) library(ggrastr) points_num <- 5000 df <- data.frame(x=rnorm(points_num), y=rnorm(points_num), c=as.factor(1:points_num %% 2)) gg <- ggplot(df, aes(x=x, y=y, color=c)) + scale_color_discrete(guide=FALSE) gg_jitter_rast <- gg + geom_jitter_rast(raster.dpi=600) print(gg_jitter_rast) #> Warning: It is deprecated to specify `guide = FALSE` to remove a guide. Please #> use `guide = "none"` instead. ![](Legacy_functions_files/figure-markdown_strict/unnamed-chunk-7-1.png) #### Tiles: Rasterize heatmaps with geom\_tile\_rast() Heatmaps also have similar issues with the default vectorized formats: library(ggplot2) library(ggrastr) coords <- expand.grid(1:500, 1:500) coords$Value <- 1 / apply(as.matrix(coords), 1, function(x) sum((x - c(50, 50))^2)^0.01) gg_tile_vec <- ggplot(coords) + geom_tile(aes(x=Var1, y=Var2, fill=Value)) gg_tile_rast <- ggplot(coords) + rasterise(geom_tile(aes(x=Var1, y=Var2, fill=Value)), dpi = 300, scale = 1) print(gg_tile_rast) ![](Legacy_functions_files/figure-markdown_strict/unnamed-chunk-8-1.png) The legacy function `geom_tile_rast()` used the following syntax: gg_tile_rast <- ggplot(coords) + geom_tile_rast(aes(x=Var1, y=Var2, fill=Value)) print(gg_tile_rast) ![](Legacy_functions_files/figure-markdown_strict/unnamed-chunk-9-1.png) Note that we can see that the rasterized plots using `ggrastr` are lighter in size when rendered to pdf: PrintFileSize(gg_tile_rast, 'Raster') #> Raster: 46.77637 Kb. PrintFileSize(gg_tile_vec, 'Vector') #> Vector: 817.8398 Kb. #### Violin plots: Rasterize violin plots with geom\_violin\_rast() One can see a similar effect with violin plots: library(ggplot2) library(ggrastr) gg_violin_vec <- ggplot(mtcars, aes(factor(cyl), mpg)) + geom_violin() gg_violin_rast <- ggplot(mtcars) + rasterise(geom_violin(aes(factor(cyl), mpg))) print(gg_violin_rast) ![](Legacy_functions_files/figure-markdown_strict/unnamed-chunk-11-1.png) The legacy function `geom_violin_rast()` had the following syntax: gg_violin_rast <- ggplot(mtcars) + geom_violin_rast(aes(factor(cyl), mpg)) print(gg_violin_rast) ![](Legacy_functions_files/figure-markdown_strict/unnamed-chunk-12-1.png) ## difference in size shown PrintFileSize(gg_tile_rast, 'Raster') #> Raster: 46.77637 Kb. PrintFileSize(gg_tile_vec, 'Vector') #> Vector: 817.8398 Kb. #### Box plots: Jitter outliers and rasterize box plots with geom\_boxplot\_jitter Another type of plot with a potentially large number of small objects is geom\_boxplot: library(ggplot2) library(ggrastr) points_num <- 5000 df <- data.frame(x=as.factor(1:points_num %% 2), y=log(abs(rcauchy(points_num)))) gg <- ggplot(df, aes(x=x, y=y)) + scale_color_discrete(guide="none") boxplot <- gg + geom_boxplot() print(boxplot) ![](Legacy_functions_files/figure-markdown_strict/unnamed-chunk-14-1.png) With a large number of objects, outlier points become noninformative. For example, here is the rendered plot with `points_num <- 1000000`. For such a large number of points, it would be better to jitter them using `geom_boxplot_jitter()`: library(ggplot2) library(ggrastr) points_num <- 500000 df <- data.frame(x=as.factor(1:points_num %% 2), y=log(abs(rcauchy(points_num)))) gg <- ggplot(df, aes(x=x, y=y)) + scale_color_discrete(guide="none") gg_box_vec <- gg + geom_boxplot_jitter(outlier.size=0.1, outlier.jitter.width=0.3, outlier.alpha=0.5) print(gg_box_vec) ![](Legacy_functions_files/figure-markdown_strict/unnamed-chunk-15-1.png) And this geom can be rasterized as well: gg_box_rast <- gg + geom_boxplot_jitter(outlier.size=0.1, outlier.jitter.width=0.3, outlier.alpha=0.5, raster.dpi=200) print(gg_box_rast) ![](Legacy_functions_files/figure-markdown_strict/unnamed-chunk-16-1.png) PrintFileSize(gg_box_rast, 'Raster') #> Raster: 116.998 Kb. PrintFileSize(gg_box_vec, 'Vector') #> Vector: 221.9131 Kb. #### Beeswarm-style plots: geom\_beeswarm\_rast and geom\_quasirandom ggrastr also allows users to create rasterized beeswarm plots. As described in the README for [ggbeeswarm](https://github.com/eclarke/ggbeeswarm), > Beeswarm plots (aka column scatter plots or violin scatter plots) are > a way of plotting points that would ordinarily overlap so that they > fall next to each other instead. In addition to reducing overplotting, > it helps visualize the density of the data at each point (similar to a > violin plot), while still showing each data point individually. The > ggrastr geom `geom_beeswarm_rast` is similar to > `ggbeeswarm::geom_beeswarm()`, but it provides a rasterized layer: library(ggplot2) library(ggrastr) ggplot(mtcars) + geom_beeswarm_rast(aes(x = factor(cyl), y=mpg), raster.dpi=600, cex=1.5) ![](Legacy_functions_files/figure-markdown_strict/unnamed-chunk-18-1.png) Again, we strongly encourage users to simply use `rasterise()`: library(ggplot2) library(ggrastr) library(ggbeeswarm,) ggplot(mtcars) + rasterise(geom_beeswarm(aes(x = factor(cyl), y=mpg))) ![](Legacy_functions_files/figure-markdown_strict/unnamed-chunk-19-1.png) Analogously, the legacy wrapper `geom_quasirandom_rast()` is much like `ggbeeswarm::geom_quasirandom()`, but with a rasterized layer: library(ggplot2) library(ggrastr) ggplot(mtcars) + geom_quasirandom_rast(aes(x = factor(cyl), y=mpg), raster.dpi=600) ![](Legacy_functions_files/figure-markdown_strict/unnamed-chunk-20-1.png) We encourage users to visit both [CRAN](https://CRAN.R-project.org/package=ggbeeswarm) and the [GitHub repo for ggbeeswam](https://github.com/eclarke/ggbeeswarm) for more details. ggrastr/vignettes/Raster_geoms.md0000644000176200001440000001574014435743246016732 0ustar liggesusers# ggrastr ## Rasterizing ggplot objects with `rasterize` When you need to plot data with many observations, storing plots completely in vector format is unsuitable: it requires tons of space and is very slow to work with in graphic editors. On the other hand, completely rasterizing the plot distorts important text content and prevents readers from editing and copying. The solution provided here within the package `ggrastr` is to rasterize layers that have a lot of data points, keeping all the rest in vector format. The simplest way to rasterize some of your layers is to call `rasterize` on the plot object: library(ggplot2) library(ggrastr) plot <- ggplot(diamonds, aes(carat, price, colour = cut)) + geom_point() rasterize(plot, layers='Point', dpi=50) ![](Raster_geoms_files/figure-markdown_strict/unnamed-chunk-1-1.png) The layer parameter here accepts the layers, which should be rasterized and can work with vectors of layer types. ## Rasterizing individual layers The same function can be applied on the level of individual layers. It allows users to rasterize only some layers of the same type: ggplot() + rasterise(geom_point(aes(carat, price, colour = cut), data=diamonds), dpi=30) + geom_point(aes(x=runif(20, 0, 5), y=runif(20, 0, 20000)), size=10, color="black", shape=8) ![](Raster_geoms_files/figure-markdown_strict/unnamed-chunk-2-1.png) Note that when the aspect ratio is distorted, the objects are rendered without distortion, i.e. the points in this example are still circles: # Points remain round across different aspect ratios plot <- ggplot(diamonds, aes(carat, price, colour = cut)) plot + rasterise(geom_point(), dpi = 72) + theme(aspect.ratio = 0.2) ![](Raster_geoms_files/figure-markdown_strict/unnamed-chunk-3-1.png) ## Advanced options ### Selecting rendering device By default, plots are rendered with [Cairo](https://CRAN.R-project.org/package=Cairo). However, users now have the option to render plots with the [ragg](https://github.com/r-lib/ragg) device. The motivation for using `ragg` is that `ragg` can be faster and has better anti-aliasing. That being said, the default ragg device also has some alpha blending quirks. Because of these quirks, users are recommended to use the `ragg_png` option to work around the alpha blending. The differences in devices are best seen at lower resolution: # The default 'cairo' at dpi=5 plot + rasterise(geom_point(), dpi = 5, dev = "cairo") ![](Raster_geoms_files/figure-markdown_strict/unnamed-chunk-4-1.png) # Using 'ragg' gives better anti-aliasing but has unexpected alpha blending plot + rasterise(geom_point(), dpi = 5, dev = "ragg") ![](Raster_geoms_files/figure-markdown_strict/unnamed-chunk-5-1.png) # Using 'ragg_png' solves the alpha blend, but requires writing a temporary file to disk plot + rasterise(geom_point(), dpi = 5, dev = "ragg_png") ![](Raster_geoms_files/figure-markdown_strict/unnamed-chunk-6-1.png) Note that facets are rendered correctly without users having to adjust the width/height settings. # Facets will not warp/distort points set.seed(123) plot + rasterise(geom_point(), dpi = 300) + facet_wrap(~ sample(1:3, nrow(diamonds), 2)) ![](Raster_geoms_files/figure-markdown_strict/unnamed-chunk-7-1.png) ### Scaling size of raster objects Users are also able to change the size of the raster objects with the parameter `scale`. The default behavior is not to modify the size with `scale=1`: # unchanged scaling, scale=1 plot <- ggplot(diamonds, aes(carat, price, colour = cut)) plot + rasterise(geom_point(), dpi = 300, scale = 1) ![](Raster_geoms_files/figure-markdown_strict/unnamed-chunk-8-1.png) Setting `scale` to values greater than 1 will increase the size of the rasterized objects. In this case, `scale=2` will double the size of the points in comparison to the original plot: # larger objects, scale > 1 plot <- ggplot(diamonds, aes(carat, price, colour = cut)) plot + rasterise(geom_point(), dpi = 300, scale = 2) ![](Raster_geoms_files/figure-markdown_strict/unnamed-chunk-9-1.png) Similarly, values less than 1 will result in smaller objects. Here we see `scale=0.5` results in points half the size of the points in the original plot above: # smaller objects, scale < 1 plot <- ggplot(diamonds, aes(carat, price, colour = cut)) plot + rasterise(geom_point(), dpi = 300, scale = 0.5) ![](Raster_geoms_files/figure-markdown_strict/unnamed-chunk-10-1.png) ### Rasterize multiple layers with lists As of ggrastr versions `>=0.2.3`, users are also able to rasterize multiple layers at once using (valid) lists. It is mainly useful when working with `geom_sf`, as it returns the list object instead of a single geom: world1 <- sf::st_as_sf(maps::map('world', plot = FALSE, fill = TRUE)) ggplot() + rasterise( list( list( geom_sf(data = world1), theme(panel.background = element_rect(fill = "skyblue")) ), list( list( geom_point(aes(x = rnorm(100, sd = 10), y = rnorm(100, sd = 10))) ), theme(panel.border = element_rect(fill = NA, colour = "blue")) ) ) ) ![](Raster_geoms_files/figure-markdown_strict/unnamed-chunk-11-1.png) ### Set the parameter ‘dpi’ globally with options(ggrastr.default.dpi=N) The parameter `dpi` is an integer which sets the desired resolution in dots per inch. With ggrastr versions `>=0.2.2`, users can set this parameter globally, using [options()](https://stat.ethz.ch/R-manual/R-devel/library/base/html/options.html). In the following example, plots will be rendered with `dpi=750` after the user sets this with `options(ggrastr.default.dpi=750)`: ## set ggrastr.default.dpi with options() options(ggrastr.default.dpi=750) plot <- ggplot(diamonds, aes(carat, price, colour = cut)) new_plot = plot + rasterise(geom_point()) + theme(aspect.ratio = 1) print(new_plot) ![](Raster_geoms_files/figure-markdown_strict/unnamed-chunk-12-1.png) ## set back to default 300 options(ggrastr.default.dpi=300) ## Other wrapper functions For legacy reasons, we have all popular geoms wrapped inside the package. However, we strongly encourage users to use the `rasterise()` function instead. - `geom_point_rast`: raster scatter plots - `geom_jitter_rast`: raster jittered scatter plots - `geom_boxplot_jitter`: boxplots that allows to jitter and rasterize outlier points - `geom_tile_rast`: raster heatmap - `geom_beeswarm_rast`: raster [bee swarm plots](https://github.com/eclarke/ggbeeswarm#geom_beeswarm) - `geom_quasirandom_rast`: raster [quasirandom scatter plot](https://github.com/eclarke/ggbeeswarm#geom_quasirandom) For more details, see the vignettes detailing these legacy functions [here](https://github.com/VPetukhov/ggrastr/blob/main/vignettes/Legacy_functions.md) (for the Markdown version) and [here](https://htmlpreview.github.io/?https://raw.githubusercontent.com/VPetukhov/ggrastr/main/doc/Legacy_functions.html) (for the HTML version). ggrastr/R/0000755000176200001440000000000014436002437012127 5ustar liggesusersggrastr/R/geom-quasirandom-rast.R0000644000176200001440000000276014435743246016507 0ustar liggesusers#' This geom is similar to \code{\link[ggbeeswarm]{geom_quasirandom}}, but creates a raster layer #' #' @inheritParams geom_point_rast #' @inheritParams ggbeeswarm::position_quasirandom #' @inheritSection ggplot2::geom_point Aesthetics #' #' @param raster.dpi integer Resolution of the rastered image in dots per inch (default=300). #' @param dev string Specifies the device used, which can be one of: \code{"cairo"}, \code{"ragg"} or \code{"ragg_png"} (default="cairo"). #' @param scale numeric Scaling factor to modify the raster object size (default=1). The parameter 'scale=1' results in an object size that is unchanged, 'scale'>1 increase the size, and 'scale'<1 decreases the size. These parameters are passed to 'height' and 'width' of grid::grid.raster(). Please refer to 'rasterise()' and 'grid::grid.raster()' for more details. #' @return geom_quasirandom plot with rasterized layer #' #' @examples #' library(ggplot2) #' library(ggrastr) #' #' ggplot(mtcars) + geom_quasirandom_rast(aes(x = factor(cyl), y = mpg), raster.dpi = 600) #' #' @export geom_quasirandom_rast <- function(..., width = NULL, varwidth = FALSE, bandwidth = 0.5, nbins = NULL, method = "quasirandom", groupOnX = NULL, dodge.width = 0, raster.dpi = getOption("ggrastr.default.dpi", 300), dev="cairo", scale=1) { rasterise(ggbeeswarm::geom_quasirandom(..., width = width, varwidth = varwidth, bandwidth = bandwidth, nbins = nbins, method = method, groupOnX = groupOnX, dodge.width = dodge.width), dpi=raster.dpi, dev=dev, scale=scale) } ggrastr/R/geom-boxplot-jitter.R0000644000176200001440000001235514436022051016165 0ustar liggesusers GeomPointRast <- ggplot2::ggproto( "GeomPointRast", ggplot2::GeomPoint, draw_panel = function(self, data, panel_params, coord, raster.dpi, dev, scale) { grob <- ggproto_parent(GeomPoint, self)$draw_panel(data, panel_params, coord) class(grob) <- c("rasteriser", class(grob)) grob$dpi <- raster.dpi grob$dev <- dev grob$scale <- scale return(grob) } ) DrawGeomBoxplotJitter <- function(data, panel_params, coord, dev="cairo", ..., outlier.jitter.width=NULL, outlier.jitter.height=0, outlier.colour = NULL, outlier.fill = NULL, outlier.shape = 19, outlier.size = 1.5, outlier.stroke = 0.5, outlier.alpha = NULL, raster=FALSE, raster.dpi=getOption("ggrastr.default.dpi", 300), raster.width=NULL, raster.height=NULL, scale = 1 ) { boxplot_grob <- ggplot2::GeomBoxplot$draw_group(data, panel_params, coord, ...) point_grob <- grep("geom_point.*", names(boxplot_grob$children)) if (length(point_grob) == 0){ return(boxplot_grob) } ifnotnull <- function(x, y) if(is.null(x)) y else x if (is.null(outlier.jitter.width)) { outlier.jitter.width <- (data$xmax - data$xmin) / 2 } x <- data$x[1] y <- data$outliers[[1]] if (outlier.jitter.width > 0 & length(y) > 1) { x <- jitter(rep(x, length(y)), amount=outlier.jitter.width) } if (outlier.jitter.height > 0 & length(y) > 1) { y <- jitter(y, amount=outlier.jitter.height) } outliers <- data.frame( x = x, y = y, colour = ifnotnull(outlier.colour, data$colour[1]), fill = ifnotnull(outlier.fill, data$fill[1]), shape = ifnotnull(outlier.shape, data$shape[1]), size = ifnotnull(outlier.size, data$size[1]), stroke = ifnotnull(outlier.stroke, data$stroke[1]), fill = NA, alpha = ifnotnull(outlier.alpha, data$alpha[1]), stringsAsFactors = FALSE ) boxplot_grob$children[[point_grob]] <- GeomPointRast$draw_panel(outliers, panel_params, coord, raster.dpi=raster.dpi, dev=dev, scale = scale) return(boxplot_grob) } GeomBoxplotJitter <- ggplot2::ggproto("GeomBoxplotJitter", ggplot2::GeomBoxplot, draw_group = DrawGeomBoxplotJitter) #' This geom is similar to \code{\link[ggplot2]{geom_boxplot}}, but allows to jitter outlier points and to raster points layer. #' #' @inheritParams ggplot2::geom_boxplot #' @inheritSection ggplot2::geom_boxplot Aesthetics #' #' @param outlier.jitter.width numeric Amount of horizontal jitter (default=NULL). The jitter is added in both positive and negative directions, #' so the total spread is twice the value specified here. If NULL, no jitter performed. #' @param outlier.jitter.height numeric Amount of horizontal jitter (default=0). The jitter is added in both positive and negative directions, #' so the total spread is twice the value specified here. #' @param raster.dpi integer Resolution of the rastered image (default=300). Ignored if \code{raster == FALSE}. #' @param dev string Specifies the device used, which can be one of: \code{"cairo"}, \code{"ragg"} or \code{"ragg_png"} (default="cairo"). #' @param stat string The statistical transformation to use on the data for this layer, either as a ggproto Geom subclass or as a string naming the stat stripped of the stat_ prefix (e.g. "count" rather than "stat_count"). Refer to ggplot2::layer. #' @param scale numeric Scaling factor to modify the raster object size (default=1). The parameter 'scale=1' results in an object size that is unchanged, 'scale'>1 increase the size, and 'scale'<1 decreases the size. These parameters are passed to 'height' and 'width' of grid::grid.raster(). Please refer to 'rasterise()' and 'grid::grid.raster()' for more details. #' @return geom_boxplot plot with rasterized layer #' #' @examples #' library(ggplot2) #' library(ggrastr) #' #' yvalues = rt(1000, df=3) #' xvalues = as.factor(1:1000 %% 2) #' ggplot() + geom_boxplot_jitter(aes(y=yvalues, x=xvalues), outlier.jitter.width = 0.1, raster = TRUE) #' #' @export geom_boxplot_jitter <- function(mapping = NULL, data = NULL, dev = "cairo", stat = "boxplot", position = "dodge", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ..., outlier.jitter.width=NULL, outlier.jitter.height=0, raster.dpi=getOption("ggrastr.default.dpi", 300), scale = 1 ) { ggplot2::layer( geom = GeomBoxplotJitter, mapping = mapping, data = data, stat = stat, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(na.rm = na.rm, outlier.jitter.width=outlier.jitter.width, outlier.jitter.height=outlier.jitter.height, raster.dpi=raster.dpi, dev=dev, scale = scale, ...)) } ggrastr/R/utils.R0000644000176200001440000000367714435743246013440 0ustar liggesusers#' Pretty theme #' #' @param show.ticks boolean Whether to show x- and y-ticks (default=TRUE). #' @param legend.pos Vector with x and y position of the legend (default=NULL). #' @return ggplot2 with plot ticks and positioned legend #' #' @examples #' library(ggplot2) #' library(ggrastr) #' #' data = rnorm(100) #' colors = (1:100/100) #' ggplot() + geom_point(aes(x=data, y=data, color=colors)) + theme_pdf(FALSE, legend.pos=c(1, 1)) #' #' @export theme_pdf <- function(show.ticks=TRUE, legend.pos=NULL) { r <- ggplot2::theme(axis.line = ggplot2::element_line(size=0.7, color = "black"), axis.text=ggplot2::element_text(size=12), axis.title.x=ggplot2::element_text(margin=ggplot2::margin(t=3, unit='pt')), axis.title.y=ggplot2::element_text(margin=ggplot2::margin(r=3, unit='pt')), legend.background = ggplot2::element_rect(fill="transparent"), legend.box.background = ggplot2::element_rect(fill=ggplot2::alpha('white', 0.7), color=ggplot2::alpha('black', 0.3)), legend.box.margin = ggplot2::margin(t=3, r=3, b=3, l=3, unit='pt'), legend.key.size = ggplot2::unit(12, "pt"), legend.margin = ggplot2::margin(t=0, r=0, b=0, l=0, unit='pt'), legend.text = ggplot2::element_text(size=10), legend.title = ggplot2::element_text(size=12), plot.margin = ggplot2::margin(t=12, r=12, b=0, l=0, unit='pt'), plot.title = ggplot2::element_text(hjust=0.5, size=14)) if (!show.ticks) { r <- r + ggplot2::theme(axis.ticks=ggplot2::element_blank(), axis.text=ggplot2::element_blank()) } if (!is.null(legend.pos)) { r <- r + ggplot2::theme(legend.position=legend.pos, legend.justification=legend.pos) } return(r) } ggrastr/R/rasterise.R0000644000176200001440000001514214436023406014255 0ustar liggesusers#' @import ggplot2 NULL #' Rasterise ggplot layers #' Takes a ggplot object or a layer as input and renders their graphical output as a raster. #' #' @param dpi integer Sets the desired resolution in dots per inch (default=NULL). #' @param dev string Specifies the device used, which can be one of: \code{"cairo"}, \code{"ragg"}, \code{"ragg_png"} or \code{"cairo_png"} (default="cairo"). #' @param scale numeric Scaling factor to modify the raster object size (default=1). The parameter 'scale=1' results in an object size that is unchanged, 'scale'>1 increase the size, and 'scale'<1 decreases the size. These parameters are passed to 'height' and 'width' of grid::grid.raster(). Please refer to 'rasterise()' and 'grid::grid.raster()' for more details. #' @param ... ignored #' @details The default \code{dpi} (\code{NULL} (i.e. let the device decide)) can conveniently be controlled by setting the option \code{"ggrastr.default.dpi"} (e.g. \code{options("ggrastr.default.dpi" = 30)} for drafting). #' @return A modified \code{Layer} object. #' @examples #' require(ggplot2) #' # `rasterise()` is used to wrap layers #' ggplot(pressure, aes(temperature, pressure)) + #' rasterise(geom_line()) #' #' # The `dpi` argument controls resolution #' ggplot(faithful, aes(eruptions, waiting)) + #' rasterise(geom_point(), dpi = 5) #' #' # The `dev` argument offers a few options for devices #' require(ragg) #' ggplot(diamonds, aes(carat, depth, z = price)) + #' rasterise(stat_summary_hex(), dev = "ragg") #' #' # The `scale` argument allows you to render a 'big' plot in small window, or vice versa. #' ggplot(faithful, aes(eruptions, waiting)) + #' rasterise(geom_point(), scale = 4) #' @rdname rasterise #' @export rasterise <- function(input, ...) UseMethod("rasterise", input) #' @param input A \code{Layer} object, typically constructed with a call to a #' \code{geom_*()} or \code{stat_*()} function. #' @author Teun van den Brand #' @rdname rasterise #' @export rasterise.Layer <- function(input, ..., dpi=NULL, dev="cairo", scale=1) { dev <- match.arg(dev, c("cairo", "ragg", "ragg_png", "cairo_png")) if (is.null(dpi)) { dpi <- getOption("ggrastr.default.dpi") } force(input) ggproto( NULL, input, draw_geom = function(self, data, layout) { grobs <- ggplot2::ggproto_parent(input, self)$draw_geom(data, layout) lapply(grobs, function(grob) { if (inherits(grob, "zeroGrob")) { return(grob) } class(grob) <- c("rasteriser", class(grob)) grob$dpi <- dpi grob$dev <- dev grob$scale <- scale return(grob) }) } ) } #' @param input input list with rasterizable ggplot objects #' @rdname rasterise #' @export rasterise.list <- function(input, ..., dpi=NULL, dev="cairo", scale=1) { # geom_sf returns a list and requires extra logic here to handle gracefully # Check if list contains layers has.layer <- rapply(input, is.layer, how = "list") has.layer <- vapply(has.layer, function(x) {any(unlist(x))}, logical(1)) if (!any(has.layer)) { stop("The input list doesn't contain any ggplot layers", call.=FALSE) } # Recurse through list elements that contain layers input[has.layer] <- lapply(input[has.layer], rasterise, dpi=dpi, dev=dev) return(input) } #' @param input ggplot plot object to rasterize #' @param layers list of layer types that should be rasterized #' @rdname rasterise #' @export rasterise.ggplot <- function(input, ..., layers=c('Point', 'Tile'), dpi=NULL, dev="cairo", scale=1) { input$layers <- lapply(input$layers, function(lay) { if (inherits(lay$geom, paste0('Geom', layers))) { rasterise(lay, dpi=dpi, dev=dev, scale=scale) } else{ lay } }) return(input) } #' @inherit rasterise #' @export rasterize rasterize <- rasterise #' @export #' @noRd #' @importFrom grid makeContext #' @method makeContext rasteriser makeContext.rasteriser <- function(x) { # Grab viewport information vp <- if (is.null(x$vp)){ grid::viewport() } else{ x$vp } width <- grid::convertWidth(unit(1, "npc"), "inch", valueOnly = TRUE) height <- grid::convertHeight(unit(1, "npc"), "inch", valueOnly = TRUE) # Grab grob metadata dpi <- x$dpi if (is.null(dpi)) { # If missing, take current DPI dpi <- grid::convertWidth(unit(1, "inch"), "pt", valueOnly = TRUE) } dev <- x$dev scale <- x$scale # Clean up grob x$dev <- NULL x$dpi <- NULL x$scale <- NULL class(x) <- setdiff(class(x), "rasteriser") # Rescale height and width if (scale <= 0 || !is.numeric(scale)) { stop("The parameter 'scale' must be set to a numeric greater than 0") } width <- width / scale height <- height / scale # Track current device dev_cur <- grDevices::dev.cur() # Reset current device upon function exit on.exit(grDevices::dev.set(dev_cur), add = TRUE) # Setup temporary device for capture if (dev == "cairo") { dev_id <- Cairo::Cairo( type = 'raster', width = width, height = height, units = "in", dpi = dpi, bg = NA )[1] } else if (dev == "ragg") { dev_id <- ragg::agg_capture( width = width, height = height, units = "in", res = dpi, background = NA ) } else { # Temporarily make a file to write png to file <- tempfile(fileext = ".png") # Destroy temporary file upon function exit on.exit(unlink(file), add = TRUE) if (dev == "cairo_png") { grDevices::png( file, width = width, height = height, units = "in", res = dpi, bg = NA, type = "cairo" ) } else { ragg::agg_png( file, width = width, height = height, units = "in", res = dpi, background = NA ) } } # Render layer grid::pushViewport(vp) grid::grid.draw(x) grid::popViewport() # Capture raster if (!dev %in% c("ragg_png", "cairo_png")) { cap <- grid::grid.cap() } grDevices::dev.off() if (dev %in% c("ragg_png", "cairo_png")) { # Read in the png file cap <- png::readPNG(file, native = FALSE) dim <- dim(cap) cap <- matrix( grDevices::rgb( red = as.vector(cap[, , 1]), green = as.vector(cap[, , 2]), blue = as.vector(cap[, , 3]), alpha = as.vector(cap[, , 4]) ), dim[1], dim[2] ) } # Forward raster grob grid::rasterGrob( cap, x = 0.5, y = 0.5, height = unit(height * scale, "inch"), width = unit(width * scale, "inch"), default.units = "npc", just = "center" ) } # Small helper function to test if x is a ggplot2 layer #' @keywords internal is.layer <- function(x) { # duplicate of hidden ggplot2:::is.layer inherits(x, "Layer") } ggrastr/R/geom-point-rast.R0000644000176200001440000000223514435743246015312 0ustar liggesusers#' This geom is similar to \code{\link[ggplot2]{geom_point}}, but creates a raster layer #' #' @inheritParams ggplot2::geom_point #' @inheritSection ggplot2::geom_point Aesthetics #' #' @import ggplot2 #' @param raster.dpi integer Resolution of the rastered image in dots per inch (default=300). #' @param dev string Specifies the device used, which can be one of: \code{"cairo"}, \code{"ragg"} or \code{"ragg_png"} (default="cairo"). #' @param scale numeric Scaling factor to modify the raster object size (default=1). The parameter 'scale=1' results in an object size that is unchanged, 'scale'>1 increase the size, and 'scale'<1 decreases the size. These parameters are passed to 'height' and 'width' of grid::grid.raster(). Please refer to 'rasterise()' and 'grid::grid.raster()' for more details. #' @return geom_point plot with rasterized layer #' #' @examples #' library(ggplot2) #' library(ggrastr) #' #' ggplot() + geom_point_rast(aes(x=rnorm(1000), y=rnorm(1000)), raster.dpi=600) #' #' @export geom_point_rast <- function(..., raster.dpi=getOption("ggrastr.default.dpi", 300), dev="cairo", scale=1) { rasterise(geom_point(...), dpi=raster.dpi, dev=dev, scale=scale) } ggrastr/R/geom-jitter-rast.R0000644000176200001440000000223714435743246015464 0ustar liggesusers#' This geom is similar to \code{\link[ggplot2]{geom_jitter}}, but creates a raster layer #' #' @inheritParams geom_point_rast #' @inheritSection ggplot2::geom_point Aesthetics #' @import ggplot2 #' @param raster.dpi integer Resolution of the rastered image in dots per inch (default=300). #' @param dev string Specifies the device used, which can be one of: \code{"cairo"}, \code{"ragg"} or \code{"ragg_png"} (default="cairo"). #' @param scale numeric Scaling factor to modify the raster object size (default=1). The parameter 'scale=1' results in an object size that is unchanged, 'scale'>1 increase the size, and 'scale'<1 decreases the size. These parameters are passed to 'height' and 'width' of grid::grid.raster(). Please refer to 'rasterise()' and 'grid::grid.raster()' for more details. #' @return geom_point_rast plot with rasterized layer #' #' @examples #' library(ggplot2) #' library(ggrastr) #' #' ggplot(mpg) + geom_jitter_rast(aes(x = factor(cyl), y = hwy), raster.dpi = 600) #' #' @export geom_jitter_rast <- function(..., raster.dpi=getOption("ggrastr.default.dpi", 300), dev="cairo", scale=1){ rasterise(geom_jitter(...), dpi=raster.dpi, dev=dev, scale=scale) } ggrastr/R/geom-tile-rast.R0000644000176200001440000000237214435743246015120 0ustar liggesusers#' This geom is similar to \code{\link[ggplot2]{geom_tile}}, but creates a raster layer #' #' @inheritParams ggplot2::geom_tile #' @inheritSection ggplot2::geom_tile Aesthetics #' #' @param raster.dpi integer Resolution of the rastered image in dots per inch (default=300). #' @param dev string Specifies the device used, which can be one of: \code{"cairo"}, \code{"ragg"} or \code{"ragg_png"} (default="cairo"). #' @param scale numeric Scaling factor to modify the raster object size (default=1). The parameter 'scale=1' results in an object size that is unchanged, 'scale'>1 increase the size, and 'scale'<1 decreases the size. These parameters are passed to 'height' and 'width' of grid::grid.raster(). Please refer to 'rasterise()' and 'grid::grid.raster()' for more details. #' @return geom_tile plot with rasterized layer #' #' @examples #' library(ggplot2) #' library(ggrastr) #' #' coords <- expand.grid(1:100, 1:100) #' coords$Value <- 1 / apply(as.matrix(coords), 1, function(x) sum((x - c(50, 50))^2)^0.01) #' ggplot(coords) + geom_tile_rast(aes(x=Var1, y=Var2, fill=Value)) #' #' @export geom_tile_rast <- function(..., raster.dpi=getOption("ggrastr.default.dpi", 300), dev="cairo", scale=1) { rasterise(geom_tile(...), dpi=raster.dpi, dev=dev, scale=scale) } ggrastr/R/geom-violin-rast.R0000644000176200001440000000222514435743246015460 0ustar liggesusers#' This geom is similar to \code{\link[ggplot2]{geom_violin}}, but creates a raster layer #' #' @inheritParams ggplot2::geom_violin #' @inheritSection ggplot2::geom_violin Aesthetics #' #' @param raster.dpi integer Resolution of the rastered image in dots per inch (default=300). #' @param dev string Specifies the device used, which can be one of: \code{"cairo"}, \code{"ragg"} or \code{"ragg_png"} (default="cairo"). #' @param scale numeric Scaling factor to modify the raster object size (default=1). The parameter 'scale=1' results in an object size that is unchanged, 'scale'>1 increase the size, and 'scale'<1 decreases the size. These parameters are passed to 'height' and 'width' of grid::grid.raster(). Please refer to 'rasterise()' and 'grid::grid.raster()' for more details. #' @return geom_violin_rast plot with rasterized layer #' #' @examples #' library(ggplot2) #' library(ggrastr) #' #' ggplot(mpg) + geom_violin_rast(aes(x = factor(cyl), y = hwy), raster.dpi = 600) #' #' @export geom_violin_rast = function(..., raster.dpi=getOption("ggrastr.default.dpi", 300), dev="cairo", scale=1){ rasterise(geom_violin(...), dpi=raster.dpi, dev=dev, scale=scale) } ggrastr/R/geom-beeswarm-rast.R0000644000176200001440000000416414435743246015771 0ustar liggesusers#' This geom is similar to \code{\link[ggbeeswarm]{geom_beeswarm}}, but creates a raster layer #' #' @inheritParams geom_point_rast #' #' @import ggplot2 #' @import ggbeeswarm #' @param priority string Method used to perform point layout (see ggbeeswarm::position_beeswarm). #' @param cex numeric Scaling for adjusting point spacing (see ggbeeswarm::position_beeswarm) #' @param groupOnX boolean Whether jitter be added to the x axis (default=NULL). if TRUE then jitter is added to the x axis and if FALSE jitter is added to the y axis. (The default NULL causes the function to guess which axis is the categorical axis based on the number of unique entries in each). Refer to see ggbeeswarm::position_beeswarm for more details. #' @param dodge.width numeric Amount by which points from different aesthetic groups will be dodged (default=0). This requires that one of the aesthetics is a factor. Refer to see ggbeeswarm::position_beeswarm for more details. #' @param raster.dpi integer Resolution of the rastered image in dots per inch (default=300). #' @param dev string Specifies the device used, which can be one of: \code{"cairo"}, \code{"ragg"} or \code{"ragg_png"} (default="cairo"). #' @param scale numeric Scaling factor to modify the raster object size (default=1). The parameter 'scale=1' results in an object size that is unchanged, 'scale'>1 increase the size, and 'scale'<1 decreases the size. These parameters are passed to 'height' and 'width' of grid::grid.raster(). Please refer to 'rasterise()' and 'grid::grid.raster()' for more details. #' @return geom_beeswarm plot with rasterized layer #' #' @examples #' library(ggplot2) #' library(ggrastr) #' #' ggplot(mtcars) + geom_beeswarm_rast(aes(x = factor(cyl), y = mpg), raster.dpi = 600, cex = 1.5) #' #' @export geom_beeswarm_rast <- function(..., priority= c("ascending", "descending", "density", "random", "none"), cex = 1, groupOnX = NULL, dodge.width = 0, raster.dpi = getOption("ggrastr.default.dpi", 300), dev="cairo", scale = 1) { rasterise(ggbeeswarm::geom_beeswarm(..., priority=priority, cex=cex, groupOnX=groupOnX, dodge.width=dodge.width), dpi=raster.dpi, dev=dev, scale=scale) } ggrastr/MD50000644000176200001440000000355314436033072012243 0ustar liggesuserscee2b7ec6cc5c1643315f04895b8c631 *DESCRIPTION 687c6924c41d553ceacac4178eeb0dc5 *LICENSE dc7329dbbb684f09fda7b6cde7fbac28 *NAMESPACE b711df3d63d5c6b93a27b0a0fb52cd53 *R/geom-beeswarm-rast.R 9f2278faa2a8079d964f9180507cc48a *R/geom-boxplot-jitter.R 537f3d60532d57a2e585477d3638031c *R/geom-jitter-rast.R f65f8bdb9084b7f8e0c8fb1110dcc6af *R/geom-point-rast.R 59c4c8f66414a432de1afb75f1b0dc14 *R/geom-quasirandom-rast.R d1a395da4d24706eedc372dd12c06280 *R/geom-tile-rast.R 015491a5011dc7b807b7fbf54ed8d454 *R/geom-violin-rast.R 1d13b8f3e9fe8de0bf29916a5a52ab67 *R/rasterise.R 80b0841a7596f0d84e786171fb31f9be *R/utils.R 392dbadc98ef0022ec369ee09faea7b7 *README.md 6bec206fec8e9d4e3e2c856943cc4238 *build/vignette.rds e7783447f246fd0112a4d1bddf387ab5 *inst/doc/Legacy_functions.R 0d6b06fdfa6fa2d22c1f8476266f5247 *inst/doc/Legacy_functions.Rmd 0e8ae4983c4ce5b0c6656fd12b231f4e *inst/doc/Legacy_functions.html 986eb16e6af137ec2fa0338040365107 *inst/doc/Raster_geoms.R 0fffbc5d9ed602227ae97419032a4cc8 *inst/doc/Raster_geoms.Rmd 1b754045a7c9187ad54f55c2e08966ac *inst/doc/Raster_geoms.html 162a540882eaabf728630ec8f181c3de *man/geom_beeswarm_rast.Rd b0c28a76100b7d6baa1161ef406d595d *man/geom_boxplot_jitter.Rd 4edd58c5bf9dedef30f31b66e09d17bc *man/geom_jitter_rast.Rd 7ea32aa8e418110dda9fed07da14c313 *man/geom_point_rast.Rd f9b16212d1d804decad3abb808e97b57 *man/geom_quasirandom_rast.Rd d6a8a828534a41b7204089aa2ef354ff *man/geom_tile_rast.Rd 3fbc03e870696a70a4d71a01c1ffd420 *man/geom_violin_rast.Rd 54dbf83b82570d486556874dfe258479 *man/rasterise.Rd 25efaa03f473ff37cba2f95370943e79 *man/rasterize.Rd 0b178227eb42084fb225ce380bfcf38e *man/theme_pdf.Rd 0d6b06fdfa6fa2d22c1f8476266f5247 *vignettes/Legacy_functions.Rmd 07a7c160d573911b86275f2039c82dc7 *vignettes/Legacy_functions.md 0fffbc5d9ed602227ae97419032a4cc8 *vignettes/Raster_geoms.Rmd e1b19a0ee4d9495e2f5e641986f211dd *vignettes/Raster_geoms.md ggrastr/inst/0000755000176200001440000000000014436026432012704 5ustar liggesusersggrastr/inst/doc/0000755000176200001440000000000014436026432013451 5ustar liggesusersggrastr/inst/doc/Raster_geoms.Rmd0000644000176200001440000001521014436002437016545 0ustar liggesusers--- title: "ggrastr" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{ggrastr} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` # ggrastr ## Rasterizing ggplot objects with `rasterize` When you need to plot data with many observations, storing plots completely in vector format is unsuitable: it requires tons of space and is very slow to work with in graphic editors. On the other hand, completely rasterizing the plot distorts important text content and prevents readers from editing and copying. The solution provided here within the package `ggrastr` is to rasterize layers that have a lot of data points, keeping all the rest in vector format. The simplest way to rasterize some of your layers is to call `rasterize` on the plot object: ```{r, fig.width=5, fig.height=5} library(ggplot2) library(ggrastr) plot <- ggplot(diamonds, aes(carat, price, colour = cut)) + geom_point() rasterize(plot, layers='Point', dpi=50) ``` The layer parameter here accepts the layers, which should be rasterized and can work with vectors of layer types. ## Rasterizing individual layers The same function can be applied on the level of individual layers. It allows users to rasterize only some layers of the same type: ```{r, fig.width=5, fig.height=5} ggplot() + rasterise(geom_point(aes(carat, price, colour = cut), data=diamonds), dpi=30) + geom_point(aes(x=runif(20, 0, 5), y=runif(20, 0, 20000)), size=10, color="black", shape=8) ``` Note that when the aspect ratio is distorted, the objects are rendered without distortion, i.e. the points in this example are still circles: ```{r, fig.width=5, fig.height=5} # Points remain round across different aspect ratios plot <- ggplot(diamonds, aes(carat, price, colour = cut)) plot + rasterise(geom_point(), dpi = 72) + theme(aspect.ratio = 0.2) ``` ## Advanced options ### Selecting rendering device By default, plots are rendered with [Cairo](https://CRAN.R-project.org/package=Cairo). However, users now have the option to render plots with the [ragg](https://github.com/r-lib/ragg) device. The motivation for using `ragg` is that `ragg` can be faster and has better anti-aliasing. That being said, the default ragg device also has some alpha blending quirks. Because of these quirks, users are recommended to use the `ragg_png` option to work around the alpha blending. The differences in devices are best seen at lower resolution: ```{r, fig.width=5, fig.height=5} # The default 'cairo' at dpi=5 plot + rasterise(geom_point(), dpi = 5, dev = "cairo") ``` ```{r, fig.width=5, fig.height=5} # Using 'ragg' gives better anti-aliasing but has unexpected alpha blending plot + rasterise(geom_point(), dpi = 5, dev = "ragg") ``` ```{r, fig.width=5, fig.height=5} # Using 'ragg_png' solves the alpha blend, but requires writing a temporary file to disk plot + rasterise(geom_point(), dpi = 5, dev = "ragg_png") ``` Note that facets are rendered correctly without users having to adjust the width/height settings. ```{r, fig.width=5, fig.height=5} # Facets will not warp/distort points set.seed(123) plot + rasterise(geom_point(), dpi = 300) + facet_wrap(~ sample(1:3, nrow(diamonds), 2)) ``` ### Scaling size of raster objects Users are also able to change the size of the raster objects with the parameter `scale`. The default behavior is not to modify the size with `scale=1`: ```{r, fig.width=5, fig.height=5} # unchanged scaling, scale=1 plot <- ggplot(diamonds, aes(carat, price, colour = cut)) plot + rasterise(geom_point(), dpi = 300, scale = 1) ``` Setting `scale` to values greater than 1 will increase the size of the rasterized objects. In this case, `scale=2` will double the size of the points in comparison to the original plot: ```{r, fig.width=5, fig.height=5} # larger objects, scale > 1 plot <- ggplot(diamonds, aes(carat, price, colour = cut)) plot + rasterise(geom_point(), dpi = 300, scale = 2) ``` Similarly, values less than 1 will result in smaller objects. Here we see `scale=0.5` results in points half the size of the points in the original plot above: ```{r, fig.width=5, fig.height=5} # smaller objects, scale < 1 plot <- ggplot(diamonds, aes(carat, price, colour = cut)) plot + rasterise(geom_point(), dpi = 300, scale = 0.5) ``` ### Rasterize multiple layers with lists As of ggrastr versions `>=0.2.3`, users are also able to rasterize multiple layers at once using (valid) lists. It is mainly useful when working with `geom_sf`, as it returns the list object instead of a single geom: ```{r, fig.width=7, fig.height=5} world1 <- sf::st_as_sf(maps::map('world', plot = FALSE, fill = TRUE)) ggplot() + rasterise( list( list( geom_sf(data = world1), theme(panel.background = element_rect(fill = "skyblue")) ), list( list( geom_point(aes(x = rnorm(100, sd = 10), y = rnorm(100, sd = 10))) ), theme(panel.border = element_rect(fill = NA, colour = "blue")) ) ) ) ``` ### Set the parameter 'dpi' globally with options(ggrastr.default.dpi=N) The parameter `dpi` is an integer which sets the desired resolution in dots per inch. With ggrastr versions `>=0.2.2`, users can set this parameter globally, using [options()](https://stat.ethz.ch/R-manual/R-devel/library/base/html/options.html). In the following example, plots will be rendered with `dpi=750` after the user sets this with `options(ggrastr.default.dpi=750)`: ```{r, fig.width=5, fig.height=5} ## set ggrastr.default.dpi with options() options(ggrastr.default.dpi=750) plot <- ggplot(diamonds, aes(carat, price, colour = cut)) new_plot = plot + rasterise(geom_point()) + theme(aspect.ratio = 1) print(new_plot) ## set back to default 300 options(ggrastr.default.dpi=300) ``` ## Other wrapper functions For legacy reasons, we have all popular geoms wrapped inside the package. However, we strongly encourage users to use the `rasterise()` function instead. * `geom_point_rast`: raster scatter plots * `geom_jitter_rast`: raster jittered scatter plots * `geom_boxplot_jitter`: boxplots that allows to jitter and rasterize outlier points * `geom_tile_rast`: raster heatmap * `geom_beeswarm_rast`: raster [bee swarm plots](https://github.com/eclarke/ggbeeswarm#geom_beeswarm) * `geom_quasirandom_rast`: raster [quasirandom scatter plot](https://github.com/eclarke/ggbeeswarm#geom_quasirandom) For more details, see the vignettes detailing these legacy functions [here](https://github.com/VPetukhov/ggrastr/blob/main/vignettes/Legacy_functions.md) (for the Markdown version) and [here](https://htmlpreview.github.io/?https://raw.githubusercontent.com/VPetukhov/ggrastr/main/doc/Legacy_functions.html) (for the HTML version). ggrastr/inst/doc/Legacy_functions.Rmd0000644000176200001440000002063514436002437017416 0ustar liggesusers--- title: "Legacy (outdated) wrapper functions" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Legacy (outdated) wrapper functions} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` # Legacy (outdated) wrapper functions For historic reasons, `ggrastr` used to be solely composed of the following functions: * `geom_point_rast`: raster scatter plots * `geom_jitter_rast`: raster jittered scatter plots * `geom_boxplot_jitter`: boxplots that allows to jitter and rasterize outlier points * `geom_tile_rast`: raster heatmap * `geom_beeswarm_rast`: raster [bee swarm plots](https://github.com/eclarke/ggbeeswarm#geom_beeswarm) * `geom_quasirandom_rast`: raster [quasirandom scatter plot](https://github.com/eclarke/ggbeeswarm#geom_quasirandom) However, we strongly encourage users to use the `rasterise()` function instead. For posterity's sake, we have only included the old vignettes here for the reference of users, along with the equivalent functions using `rasterise()`. #### Points: Rasterize scatter plots with geom_point_rast() Sometimes you need to publish a figure in a vector format: ```{r, fig.width=5, fig.height=5} library(ggplot2) library(ggrastr) points_num <- 10000 df <- data.frame(x=rnorm(points_num), y=rnorm(points_num), c=as.factor(1:points_num %% 2)) gg <- ggplot(df, aes(x=x, y=y, color=c)) + scale_color_discrete(guide="none") gg_vec <- gg + geom_point(size=0.5) print(gg_vec) ``` But in other cases, your figure contains thousands of points, e.g. try `points_num <- 500000` in the example above, and you will notice the performance issues---it takes significantly longer to render the plot. In this case, a reasonable solution would be to rasterize the plot. But the problem is that all text becomes rasterized as well. Raster layers with `ggrastr` were developed to prevent such a situation, using `rasterized ```{r, fig.width=5, fig.height=5} gg_rasterized <- gg + rasterise(geom_point(), dpi = 300, scale = 1) print(gg_rasterized) ``` The legacy function used in older versions of ggrastr was `geom_point_rast()`: ```{r, fig.width=5, fig.height=5} gg_rast <- gg + geom_point_rast(size=0.5) print(gg_rast) ``` The plots look the same, but the difference in size can be seen when they are exported to pdfs. Unfortunately, there is a longer rendering time to produce such plots: ```{r} PrintFileSize <- function(gg, name) { invisible(ggsave('tmp.pdf', gg, width=4, height=4)) cat(name, ': ', file.info('tmp.pdf')$size / 1024, ' Kb.\n', sep = '') unlink('tmp.pdf') } PrintFileSize(gg_rast, 'Raster') PrintFileSize(gg_vec, 'Vector') ``` As expected, the difference becomes larger with growth of number of points: ```{r} points_num <- 1000000 df <- data.frame(x=rnorm(points_num), y=rnorm(points_num), c=as.factor(1:points_num %% 2)) gg <- ggplot(df, aes(x=x, y=y, color=c)) + scale_color_discrete(guide="none") gg_vec <- gg + geom_point(size=0.5) gg_rast <- gg + geom_point_rast(size=0.5) PrintFileSize(gg_rast, 'Raster') PrintFileSize(gg_vec, 'Vector') ``` #### Jitter: Rasterize jittered scatter plots with geom_jitter_rast() Users may also opt to create rasterized scatter plots with jitter: ```{r, fig.width=5, fig.height=5} library(ggplot2) library(ggrastr) points_num <- 5000 df <- data.frame(x=rnorm(points_num), y=rnorm(points_num), c=as.factor(1:points_num %% 2)) gg <- ggplot(df, aes(x=x, y=y, color=c)) + scale_color_discrete(guide="none") gg_jitter_rast <- gg + rasterise(geom_jitter(), dpi = 300, scale = 1) print(gg_jitter_rast) ``` The legacy wrapper `geom_jitter_rast()` used the following syntax: ```{r, fig.width=5, fig.height=5} library(ggplot2) library(ggrastr) points_num <- 5000 df <- data.frame(x=rnorm(points_num), y=rnorm(points_num), c=as.factor(1:points_num %% 2)) gg <- ggplot(df, aes(x=x, y=y, color=c)) + scale_color_discrete(guide=FALSE) gg_jitter_rast <- gg + geom_jitter_rast(raster.dpi=600) print(gg_jitter_rast) ``` #### Tiles: Rasterize heatmaps with geom_tile_rast() Heatmaps also have similar issues with the default vectorized formats: ```{r, fig.width=5, fig.height=5} library(ggplot2) library(ggrastr) coords <- expand.grid(1:500, 1:500) coords$Value <- 1 / apply(as.matrix(coords), 1, function(x) sum((x - c(50, 50))^2)^0.01) gg_tile_vec <- ggplot(coords) + geom_tile(aes(x=Var1, y=Var2, fill=Value)) gg_tile_rast <- ggplot(coords) + rasterise(geom_tile(aes(x=Var1, y=Var2, fill=Value)), dpi = 300, scale = 1) print(gg_tile_rast) ``` The legacy function `geom_tile_rast()` used the following syntax: ```{r, fig.width=5, fig.height=5} gg_tile_rast <- ggplot(coords) + geom_tile_rast(aes(x=Var1, y=Var2, fill=Value)) print(gg_tile_rast) ``` Note that we can see that the rasterized plots using `ggrastr` are lighter in size when rendered to pdf: ```{r} PrintFileSize(gg_tile_rast, 'Raster') PrintFileSize(gg_tile_vec, 'Vector') ``` #### Violin plots: Rasterize violin plots with geom_violin_rast() One can see a similar effect with violin plots: ```{r, fig.width=5, fig.height=5} library(ggplot2) library(ggrastr) gg_violin_vec <- ggplot(mtcars, aes(factor(cyl), mpg)) + geom_violin() gg_violin_rast <- ggplot(mtcars) + rasterise(geom_violin(aes(factor(cyl), mpg))) print(gg_violin_rast) ``` The legacy function `geom_violin_rast()` had the following syntax: ```{r, fig.width=5, fig.height=5} gg_violin_rast <- ggplot(mtcars) + geom_violin_rast(aes(factor(cyl), mpg)) print(gg_violin_rast) ``` ```{r} ## difference in size shown PrintFileSize(gg_tile_rast, 'Raster') PrintFileSize(gg_tile_vec, 'Vector') ``` #### Box plots: Jitter outliers and rasterize box plots with geom_boxplot_jitter Another type of plot with a potentially large number of small objects is geom_boxplot: ```{r, fig.width=5, fig.height=5} library(ggplot2) library(ggrastr) points_num <- 5000 df <- data.frame(x=as.factor(1:points_num %% 2), y=log(abs(rcauchy(points_num)))) gg <- ggplot(df, aes(x=x, y=y)) + scale_color_discrete(guide="none") boxplot <- gg + geom_boxplot() print(boxplot) ``` With a large number of objects, outlier points become noninformative. For example, here is the rendered plot with `points_num <- 1000000`. For such a large number of points, it would be better to jitter them using `geom_boxplot_jitter()`: ```{r, fig.width=5, fig.height=5} library(ggplot2) library(ggrastr) points_num <- 500000 df <- data.frame(x=as.factor(1:points_num %% 2), y=log(abs(rcauchy(points_num)))) gg <- ggplot(df, aes(x=x, y=y)) + scale_color_discrete(guide="none") gg_box_vec <- gg + geom_boxplot_jitter(outlier.size=0.1, outlier.jitter.width=0.3, outlier.alpha=0.5) print(gg_box_vec) ``` And this geom can be rasterized as well: ```{r, fig.width=5, fig.height=5} gg_box_rast <- gg + geom_boxplot_jitter(outlier.size=0.1, outlier.jitter.width=0.3, outlier.alpha=0.5, raster.dpi=200) print(gg_box_rast) ``` ```{r} PrintFileSize(gg_box_rast, 'Raster') PrintFileSize(gg_box_vec, 'Vector') ``` #### Beeswarm-style plots: geom_beeswarm_rast and geom_quasirandom ggrastr also allows users to create rasterized beeswarm plots. As described in the README for [ggbeeswarm](https://github.com/eclarke/ggbeeswarm), > Beeswarm plots (aka column scatter plots or violin scatter plots) are a way of plotting points that would ordinarily overlap so that they fall next to each other instead. In addition to reducing overplotting, it helps visualize the density of the data at each point (similar to a violin plot), while still showing each data point individually. The ggrastr geom `geom_beeswarm_rast` is similar to `ggbeeswarm::geom_beeswarm()`, but it provides a rasterized layer: ```{r, fig.width=5, fig.height=5} library(ggplot2) library(ggrastr) ggplot(mtcars) + geom_beeswarm_rast(aes(x = factor(cyl), y=mpg), raster.dpi=600, cex=1.5) ``` Again, we strongly encourage users to simply use `rasterise()`: ```{r, fig.width=5, fig.height=5} library(ggplot2) library(ggrastr) library(ggbeeswarm,) ggplot(mtcars) + rasterise(geom_beeswarm(aes(x = factor(cyl), y=mpg))) ``` Analogously, the legacy wrapper `geom_quasirandom_rast()` is much like `ggbeeswarm::geom_quasirandom()`, but with a rasterized layer: ```{r, fig.width=5, fig.height=5} library(ggplot2) library(ggrastr) ggplot(mtcars) + geom_quasirandom_rast(aes(x = factor(cyl), y=mpg), raster.dpi=600) ``` We encourage users to visit both [CRAN](https://CRAN.R-project.org/package=ggbeeswarm) and the [GitHub repo for ggbeeswam](https://github.com/eclarke/ggbeeswarm) for more details. ggrastr/inst/doc/Legacy_functions.R0000644000176200001440000001260214436026363017074 0ustar liggesusers## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ---- fig.width=5, fig.height=5----------------------------------------------- library(ggplot2) library(ggrastr) points_num <- 10000 df <- data.frame(x=rnorm(points_num), y=rnorm(points_num), c=as.factor(1:points_num %% 2)) gg <- ggplot(df, aes(x=x, y=y, color=c)) + scale_color_discrete(guide="none") gg_vec <- gg + geom_point(size=0.5) print(gg_vec) ## ---- fig.width=5, fig.height=5----------------------------------------------- gg_rasterized <- gg + rasterise(geom_point(), dpi = 300, scale = 1) print(gg_rasterized) ## ---- fig.width=5, fig.height=5----------------------------------------------- gg_rast <- gg + geom_point_rast(size=0.5) print(gg_rast) ## ----------------------------------------------------------------------------- PrintFileSize <- function(gg, name) { invisible(ggsave('tmp.pdf', gg, width=4, height=4)) cat(name, ': ', file.info('tmp.pdf')$size / 1024, ' Kb.\n', sep = '') unlink('tmp.pdf') } PrintFileSize(gg_rast, 'Raster') PrintFileSize(gg_vec, 'Vector') ## ----------------------------------------------------------------------------- points_num <- 1000000 df <- data.frame(x=rnorm(points_num), y=rnorm(points_num), c=as.factor(1:points_num %% 2)) gg <- ggplot(df, aes(x=x, y=y, color=c)) + scale_color_discrete(guide="none") gg_vec <- gg + geom_point(size=0.5) gg_rast <- gg + geom_point_rast(size=0.5) PrintFileSize(gg_rast, 'Raster') PrintFileSize(gg_vec, 'Vector') ## ---- fig.width=5, fig.height=5----------------------------------------------- library(ggplot2) library(ggrastr) points_num <- 5000 df <- data.frame(x=rnorm(points_num), y=rnorm(points_num), c=as.factor(1:points_num %% 2)) gg <- ggplot(df, aes(x=x, y=y, color=c)) + scale_color_discrete(guide="none") gg_jitter_rast <- gg + rasterise(geom_jitter(), dpi = 300, scale = 1) print(gg_jitter_rast) ## ---- fig.width=5, fig.height=5----------------------------------------------- library(ggplot2) library(ggrastr) points_num <- 5000 df <- data.frame(x=rnorm(points_num), y=rnorm(points_num), c=as.factor(1:points_num %% 2)) gg <- ggplot(df, aes(x=x, y=y, color=c)) + scale_color_discrete(guide=FALSE) gg_jitter_rast <- gg + geom_jitter_rast(raster.dpi=600) print(gg_jitter_rast) ## ---- fig.width=5, fig.height=5----------------------------------------------- library(ggplot2) library(ggrastr) coords <- expand.grid(1:500, 1:500) coords$Value <- 1 / apply(as.matrix(coords), 1, function(x) sum((x - c(50, 50))^2)^0.01) gg_tile_vec <- ggplot(coords) + geom_tile(aes(x=Var1, y=Var2, fill=Value)) gg_tile_rast <- ggplot(coords) + rasterise(geom_tile(aes(x=Var1, y=Var2, fill=Value)), dpi = 300, scale = 1) print(gg_tile_rast) ## ---- fig.width=5, fig.height=5----------------------------------------------- gg_tile_rast <- ggplot(coords) + geom_tile_rast(aes(x=Var1, y=Var2, fill=Value)) print(gg_tile_rast) ## ----------------------------------------------------------------------------- PrintFileSize(gg_tile_rast, 'Raster') PrintFileSize(gg_tile_vec, 'Vector') ## ---- fig.width=5, fig.height=5----------------------------------------------- library(ggplot2) library(ggrastr) gg_violin_vec <- ggplot(mtcars, aes(factor(cyl), mpg)) + geom_violin() gg_violin_rast <- ggplot(mtcars) + rasterise(geom_violin(aes(factor(cyl), mpg))) print(gg_violin_rast) ## ---- fig.width=5, fig.height=5----------------------------------------------- gg_violin_rast <- ggplot(mtcars) + geom_violin_rast(aes(factor(cyl), mpg)) print(gg_violin_rast) ## ----------------------------------------------------------------------------- ## difference in size shown PrintFileSize(gg_tile_rast, 'Raster') PrintFileSize(gg_tile_vec, 'Vector') ## ---- fig.width=5, fig.height=5----------------------------------------------- library(ggplot2) library(ggrastr) points_num <- 5000 df <- data.frame(x=as.factor(1:points_num %% 2), y=log(abs(rcauchy(points_num)))) gg <- ggplot(df, aes(x=x, y=y)) + scale_color_discrete(guide="none") boxplot <- gg + geom_boxplot() print(boxplot) ## ---- fig.width=5, fig.height=5----------------------------------------------- library(ggplot2) library(ggrastr) points_num <- 500000 df <- data.frame(x=as.factor(1:points_num %% 2), y=log(abs(rcauchy(points_num)))) gg <- ggplot(df, aes(x=x, y=y)) + scale_color_discrete(guide="none") gg_box_vec <- gg + geom_boxplot_jitter(outlier.size=0.1, outlier.jitter.width=0.3, outlier.alpha=0.5) print(gg_box_vec) ## ---- fig.width=5, fig.height=5----------------------------------------------- gg_box_rast <- gg + geom_boxplot_jitter(outlier.size=0.1, outlier.jitter.width=0.3, outlier.alpha=0.5, raster.dpi=200) print(gg_box_rast) ## ----------------------------------------------------------------------------- PrintFileSize(gg_box_rast, 'Raster') PrintFileSize(gg_box_vec, 'Vector') ## ---- fig.width=5, fig.height=5----------------------------------------------- library(ggplot2) library(ggrastr) ggplot(mtcars) + geom_beeswarm_rast(aes(x = factor(cyl), y=mpg), raster.dpi=600, cex=1.5) ## ---- fig.width=5, fig.height=5----------------------------------------------- library(ggplot2) library(ggrastr) library(ggbeeswarm,) ggplot(mtcars) + rasterise(geom_beeswarm(aes(x = factor(cyl), y=mpg))) ## ---- fig.width=5, fig.height=5----------------------------------------------- library(ggplot2) library(ggrastr) ggplot(mtcars) + geom_quasirandom_rast(aes(x = factor(cyl), y=mpg), raster.dpi=600) ggrastr/inst/doc/Legacy_functions.html0000644000176200001440000662255014436026364017657 0ustar liggesusers Legacy (outdated) wrapper functions

Legacy (outdated) wrapper functions

Legacy (outdated) wrapper functions

For historic reasons, ggrastr used to be solely composed of the following functions:

  • geom_point_rast: raster scatter plots
  • geom_jitter_rast: raster jittered scatter plots
  • geom_boxplot_jitter: boxplots that allows to jitter and rasterize outlier points
  • geom_tile_rast: raster heatmap
  • geom_beeswarm_rast: raster bee swarm plots
  • geom_quasirandom_rast: raster quasirandom scatter plot

However, we strongly encourage users to use the rasterise() function instead. For posterity’s sake, we have only included the old vignettes here for the reference of users, along with the equivalent functions using rasterise().

Points: Rasterize scatter plots with geom_point_rast()

Sometimes you need to publish a figure in a vector format:

library(ggplot2)
library(ggrastr)
points_num <- 10000
df <- data.frame(x=rnorm(points_num), y=rnorm(points_num), c=as.factor(1:points_num %% 2))
gg <- ggplot(df, aes(x=x, y=y, color=c)) + scale_color_discrete(guide="none")
gg_vec <- gg + geom_point(size=0.5)
print(gg_vec)

But in other cases, your figure contains thousands of points, e.g. try points_num <- 500000 in the example above, and you will notice the performance issues—it takes significantly longer to render the plot.

In this case, a reasonable solution would be to rasterize the plot. But the problem is that all text becomes rasterized as well.

Raster layers with ggrastr were developed to prevent such a situation, using `rasterized

gg_rasterized <- gg + rasterise(geom_point(), dpi = 300, scale = 1)
print(gg_rasterized)

The legacy function used in older versions of ggrastr was geom_point_rast():

gg_rast <- gg + geom_point_rast(size=0.5)
print(gg_rast)

The plots look the same, but the difference in size can be seen when they are exported to pdfs. Unfortunately, there is a longer rendering time to produce such plots:

PrintFileSize <- function(gg, name) {
  invisible(ggsave('tmp.pdf', gg, width=4, height=4))
  cat(name, ': ', file.info('tmp.pdf')$size / 1024, ' Kb.\n', sep = '')
  unlink('tmp.pdf')
}
PrintFileSize(gg_rast, 'Raster')
#> Raster: 313.1133 Kb.
PrintFileSize(gg_vec, 'Vector')
#> Vector: 556.8623 Kb.

As expected, the difference becomes larger with growth of number of points:

points_num <- 1000000
df <- data.frame(x=rnorm(points_num), y=rnorm(points_num), c=as.factor(1:points_num %% 2))
gg <- ggplot(df, aes(x=x, y=y, color=c)) + scale_color_discrete(guide="none")
gg_vec <- gg + geom_point(size=0.5)
gg_rast <- gg + geom_point_rast(size=0.5)
PrintFileSize(gg_rast, 'Raster')
#> Raster: 382.0195 Kb.
PrintFileSize(gg_vec, 'Vector')
#> Vector: 54856.23 Kb.

Jitter: Rasterize jittered scatter plots with geom_jitter_rast()

Users may also opt to create rasterized scatter plots with jitter:

library(ggplot2)
library(ggrastr)
points_num <- 5000 
df <- data.frame(x=rnorm(points_num), y=rnorm(points_num), c=as.factor(1:points_num %% 2))
gg <- ggplot(df, aes(x=x, y=y, color=c)) + scale_color_discrete(guide="none")
gg_jitter_rast <- gg + rasterise(geom_jitter(), dpi = 300, scale = 1)
print(gg_jitter_rast)

The legacy wrapper geom_jitter_rast() used the following syntax:

library(ggplot2)
library(ggrastr)

points_num <- 5000 
df <- data.frame(x=rnorm(points_num), y=rnorm(points_num), c=as.factor(1:points_num %% 2))
gg <- ggplot(df, aes(x=x, y=y, color=c)) + scale_color_discrete(guide=FALSE)

gg_jitter_rast <- gg + geom_jitter_rast(raster.dpi=600)
print(gg_jitter_rast)
#> Warning: The `guide` argument in `scale_*()` cannot be `FALSE`. This was deprecated in
#> ggplot2 3.3.4.
#> ℹ Please use "none" instead.
#> This warning is displayed once every 8 hours.
#> Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
#> generated.

Tiles: Rasterize heatmaps with geom_tile_rast()

Heatmaps also have similar issues with the default vectorized formats:

library(ggplot2)
library(ggrastr)
coords <- expand.grid(1:500, 1:500)
coords$Value <- 1 / apply(as.matrix(coords), 1, function(x) sum((x - c(50, 50))^2)^0.01)
gg_tile_vec <- ggplot(coords) + geom_tile(aes(x=Var1, y=Var2, fill=Value))
gg_tile_rast <- ggplot(coords) + rasterise(geom_tile(aes(x=Var1, y=Var2, fill=Value)), dpi = 300, scale = 1)
print(gg_tile_rast)

The legacy function geom_tile_rast() used the following syntax:

gg_tile_rast <- ggplot(coords) + geom_tile_rast(aes(x=Var1, y=Var2, fill=Value))
print(gg_tile_rast)

Note that we can see that the rasterized plots using ggrastr are lighter in size when rendered to pdf:

PrintFileSize(gg_tile_rast, 'Raster')
#> Raster: 46.77637 Kb.
PrintFileSize(gg_tile_vec, 'Vector')
#> Vector: 817.8408 Kb.

Violin plots: Rasterize violin plots with geom_violin_rast()

One can see a similar effect with violin plots:

library(ggplot2)
library(ggrastr)
gg_violin_vec <- ggplot(mtcars, aes(factor(cyl), mpg)) + geom_violin()
gg_violin_rast <- ggplot(mtcars) + rasterise(geom_violin(aes(factor(cyl), mpg)))
print(gg_violin_rast)

The legacy function geom_violin_rast() had the following syntax:

gg_violin_rast <- ggplot(mtcars) + geom_violin_rast(aes(factor(cyl), mpg))
print(gg_violin_rast)

## difference in size shown
PrintFileSize(gg_tile_rast, 'Raster')
#> Raster: 46.77637 Kb.
PrintFileSize(gg_tile_vec, 'Vector')
#> Vector: 817.8408 Kb.

Box plots: Jitter outliers and rasterize box plots with geom_boxplot_jitter

Another type of plot with a potentially large number of small objects is geom_boxplot:

library(ggplot2)
library(ggrastr)
points_num <- 5000
df <- data.frame(x=as.factor(1:points_num %% 2), y=log(abs(rcauchy(points_num))))
gg <- ggplot(df, aes(x=x, y=y)) + scale_color_discrete(guide="none")
boxplot <- gg + geom_boxplot()
print(boxplot)

With a large number of objects, outlier points become noninformative. For example, here is the rendered plot with points_num <- 1000000.

For such a large number of points, it would be better to jitter them using geom_boxplot_jitter():

library(ggplot2)
library(ggrastr)
points_num <- 500000
df <- data.frame(x=as.factor(1:points_num %% 2), y=log(abs(rcauchy(points_num))))
gg <- ggplot(df, aes(x=x, y=y)) + scale_color_discrete(guide="none")
gg_box_vec <- gg + geom_boxplot_jitter(outlier.size=0.1, outlier.jitter.width=0.3, outlier.alpha=0.5)
print(gg_box_vec)

And this geom can be rasterized as well:

gg_box_rast <- gg + geom_boxplot_jitter(outlier.size=0.1, outlier.jitter.width=0.3, outlier.alpha=0.5, raster.dpi=200)
print(gg_box_rast)

PrintFileSize(gg_box_rast, 'Raster')
#> Raster: 114.3164 Kb.
PrintFileSize(gg_box_vec, 'Vector')
#> Vector: 217.7812 Kb.

Beeswarm-style plots: geom_beeswarm_rast and geom_quasirandom

ggrastr also allows users to create rasterized beeswarm plots. As described in the README for ggbeeswarm,

Beeswarm plots (aka column scatter plots or violin scatter plots) are a way of plotting points that would ordinarily overlap so that they fall next to each other instead. In addition to reducing overplotting, it helps visualize the density of the data at each point (similar to a violin plot), while still showing each data point individually. The ggrastr geom geom_beeswarm_rast is similar to ggbeeswarm::geom_beeswarm(), but it provides a rasterized layer:

library(ggplot2)
library(ggrastr)
ggplot(mtcars) + geom_beeswarm_rast(aes(x = factor(cyl), y=mpg), raster.dpi=600, cex=1.5)

Again, we strongly encourage users to simply use rasterise():

library(ggplot2)
library(ggrastr)
library(ggbeeswarm,)
#> Warning: package 'ggbeeswarm' was built under R version 4.1.2
ggplot(mtcars) + rasterise(geom_beeswarm(aes(x = factor(cyl), y=mpg)))

Analogously, the legacy wrapper geom_quasirandom_rast() is much like ggbeeswarm::geom_quasirandom(), but with a rasterized layer:

library(ggplot2)
library(ggrastr)
ggplot(mtcars) + geom_quasirandom_rast(aes(x = factor(cyl), y=mpg), raster.dpi=600)

We encourage users to visit both CRAN and the GitHub repo for ggbeeswam for more details.

ggrastr/inst/doc/Raster_geoms.R0000644000176200001440000000625514436026432016236 0ustar liggesusers## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ---- fig.width=5, fig.height=5----------------------------------------------- library(ggplot2) library(ggrastr) plot <- ggplot(diamonds, aes(carat, price, colour = cut)) + geom_point() rasterize(plot, layers='Point', dpi=50) ## ---- fig.width=5, fig.height=5----------------------------------------------- ggplot() + rasterise(geom_point(aes(carat, price, colour = cut), data=diamonds), dpi=30) + geom_point(aes(x=runif(20, 0, 5), y=runif(20, 0, 20000)), size=10, color="black", shape=8) ## ---- fig.width=5, fig.height=5----------------------------------------------- # Points remain round across different aspect ratios plot <- ggplot(diamonds, aes(carat, price, colour = cut)) plot + rasterise(geom_point(), dpi = 72) + theme(aspect.ratio = 0.2) ## ---- fig.width=5, fig.height=5----------------------------------------------- # The default 'cairo' at dpi=5 plot + rasterise(geom_point(), dpi = 5, dev = "cairo") ## ---- fig.width=5, fig.height=5----------------------------------------------- # Using 'ragg' gives better anti-aliasing but has unexpected alpha blending plot + rasterise(geom_point(), dpi = 5, dev = "ragg") ## ---- fig.width=5, fig.height=5----------------------------------------------- # Using 'ragg_png' solves the alpha blend, but requires writing a temporary file to disk plot + rasterise(geom_point(), dpi = 5, dev = "ragg_png") ## ---- fig.width=5, fig.height=5----------------------------------------------- # Facets will not warp/distort points set.seed(123) plot + rasterise(geom_point(), dpi = 300) + facet_wrap(~ sample(1:3, nrow(diamonds), 2)) ## ---- fig.width=5, fig.height=5----------------------------------------------- # unchanged scaling, scale=1 plot <- ggplot(diamonds, aes(carat, price, colour = cut)) plot + rasterise(geom_point(), dpi = 300, scale = 1) ## ---- fig.width=5, fig.height=5----------------------------------------------- # larger objects, scale > 1 plot <- ggplot(diamonds, aes(carat, price, colour = cut)) plot + rasterise(geom_point(), dpi = 300, scale = 2) ## ---- fig.width=5, fig.height=5----------------------------------------------- # smaller objects, scale < 1 plot <- ggplot(diamonds, aes(carat, price, colour = cut)) plot + rasterise(geom_point(), dpi = 300, scale = 0.5) ## ---- fig.width=7, fig.height=5----------------------------------------------- world1 <- sf::st_as_sf(maps::map('world', plot = FALSE, fill = TRUE)) ggplot() + rasterise( list( list( geom_sf(data = world1), theme(panel.background = element_rect(fill = "skyblue")) ), list( list( geom_point(aes(x = rnorm(100, sd = 10), y = rnorm(100, sd = 10))) ), theme(panel.border = element_rect(fill = NA, colour = "blue")) ) ) ) ## ---- fig.width=5, fig.height=5----------------------------------------------- ## set ggrastr.default.dpi with options() options(ggrastr.default.dpi=750) plot <- ggplot(diamonds, aes(carat, price, colour = cut)) new_plot = plot + rasterise(geom_point()) + theme(aspect.ratio = 1) print(new_plot) ## set back to default 300 options(ggrastr.default.dpi=300) ggrastr/inst/doc/Raster_geoms.html0000644000176200001440000634330014436026432017002 0ustar liggesusers ggrastr

ggrastr

ggrastr

Rasterizing ggplot objects with rasterize

When you need to plot data with many observations, storing plots completely in vector format is unsuitable: it requires tons of space and is very slow to work with in graphic editors. On the other hand, completely rasterizing the plot distorts important text content and prevents readers from editing and copying. The solution provided here within the package ggrastr is to rasterize layers that have a lot of data points, keeping all the rest in vector format.

The simplest way to rasterize some of your layers is to call rasterize on the plot object:

library(ggplot2)
library(ggrastr)

plot <- ggplot(diamonds, aes(carat, price, colour = cut)) +
  geom_point()

rasterize(plot, layers='Point', dpi=50)

The layer parameter here accepts the layers, which should be rasterized and can work with vectors of layer types.

Rasterizing individual layers

The same function can be applied on the level of individual layers. It allows users to rasterize only some layers of the same type:

ggplot() + 
  rasterise(geom_point(aes(carat, price, colour = cut), data=diamonds), dpi=30) +
  geom_point(aes(x=runif(20, 0, 5), y=runif(20, 0, 20000)), size=10, color="black", shape=8)

Note that when the aspect ratio is distorted, the objects are rendered without distortion, i.e. the points in this example are still circles:

# Points remain round across different aspect ratios
plot <- ggplot(diamonds, aes(carat, price, colour = cut))
plot + rasterise(geom_point(), dpi = 72) + theme(aspect.ratio = 0.2)

Advanced options

Selecting rendering device

By default, plots are rendered with Cairo. However, users now have the option to render plots with the ragg device. The motivation for using ragg is that ragg can be faster and has better anti-aliasing. That being said, the default ragg device also has some alpha blending quirks. Because of these quirks, users are recommended to use the ragg_png option to work around the alpha blending.

The differences in devices are best seen at lower resolution:

# The default 'cairo' at dpi=5
plot + rasterise(geom_point(), dpi = 5, dev = "cairo")

# Using 'ragg' gives better anti-aliasing but has unexpected alpha blending
plot + rasterise(geom_point(), dpi = 5, dev = "ragg")

# Using 'ragg_png' solves the alpha blend, but requires writing a temporary file to disk
plot + rasterise(geom_point(), dpi = 5, dev = "ragg_png")

Note that facets are rendered correctly without users having to adjust the width/height settings.

# Facets will not warp/distort points
set.seed(123)
plot + rasterise(geom_point(), dpi = 300) + facet_wrap(~ sample(1:3, nrow(diamonds), 2))

Scaling size of raster objects

Users are also able to change the size of the raster objects with the parameter scale. The default behavior is not to modify the size with scale=1:

# unchanged scaling, scale=1
plot <- ggplot(diamonds, aes(carat, price, colour = cut))
plot + rasterise(geom_point(), dpi = 300, scale = 1)

Setting scale to values greater than 1 will increase the size of the rasterized objects. In this case, scale=2 will double the size of the points in comparison to the original plot:

# larger objects, scale > 1
plot <- ggplot(diamonds, aes(carat, price, colour = cut))
plot + rasterise(geom_point(), dpi = 300, scale = 2)

Similarly, values less than 1 will result in smaller objects. Here we see scale=0.5 results in points half the size of the points in the original plot above:

# smaller objects, scale < 1
plot <- ggplot(diamonds, aes(carat, price, colour = cut))
plot + rasterise(geom_point(), dpi = 300, scale = 0.5)

Rasterize multiple layers with lists

As of ggrastr versions >=0.2.3, users are also able to rasterize multiple layers at once using (valid) lists. It is mainly useful when working with geom_sf, as it returns the list object instead of a single geom:

world1 <- sf::st_as_sf(maps::map('world', plot = FALSE, fill = TRUE))
ggplot() + rasterise(
  list(
    list(
      geom_sf(data = world1),
      theme(panel.background = element_rect(fill = "skyblue"))
    ),
    list(
      list(
        geom_point(aes(x = rnorm(100, sd = 10), y = rnorm(100, sd = 10)))
      ),
      theme(panel.border = element_rect(fill = NA, colour = "blue"))
    )
  )
)

Set the parameter ‘dpi’ globally with options(ggrastr.default.dpi=N)

The parameter dpi is an integer which sets the desired resolution in dots per inch. With ggrastr versions >=0.2.2, users can set this parameter globally, using options(). In the following example, plots will be rendered with dpi=750 after the user sets this with options(ggrastr.default.dpi=750):

## set ggrastr.default.dpi with options()
options(ggrastr.default.dpi=750)

plot <- ggplot(diamonds, aes(carat, price, colour = cut))
new_plot = plot + rasterise(geom_point()) + theme(aspect.ratio = 1)
print(new_plot)


## set back to default 300
options(ggrastr.default.dpi=300)

Other wrapper functions

For legacy reasons, we have all popular geoms wrapped inside the package. However, we strongly encourage users to use the rasterise() function instead.

  • geom_point_rast: raster scatter plots
  • geom_jitter_rast: raster jittered scatter plots
  • geom_boxplot_jitter: boxplots that allows to jitter and rasterize outlier points
  • geom_tile_rast: raster heatmap
  • geom_beeswarm_rast: raster bee swarm plots
  • geom_quasirandom_rast: raster quasirandom scatter plot

For more details, see the vignettes detailing these legacy functions here (for the Markdown version) and here (for the HTML version).