### Example: Capture and Replay a Plot Source: https://ragg.r-lib.org/reference/agg_record.html This example demonstrates capturing drawing instructions using `agg_record()`, plotting to it, saving the recorded plot with `recordPlot()`, and then replaying it on a different device (`agg_png`). This process allows for efficient storage and reproduction of plots. ```R # Capture drawing instructions agg_record() plot(1:10, 1:10) rec <- recordPlot() dev.off() #> agg_record_20e61155b56e #> 2 # Replay these on another device file <- tempfile(fileext = '.png') agg_png(file) replayPlot(rec) dev.off() #> agg_record_20e61155b56e #> 2 ``` -------------------------------- ### Render a plot to a TIFF file Source: https://ragg.r-lib.org/reference/agg_tiff.html Example usage showing how to initialize a TIFF device with compression, draw a plot, and close the device. ```R file <- tempfile(fileext = '.tiff') # Use jpeg compression agg_tiff(file, compression = 'lzw+p') plot(sin, -pi, 2*pi) dev.off() ``` -------------------------------- ### Create a WebP file and plot Source: https://ragg.r-lib.org/reference/agg_webp.html Example of how to use agg_webp to create a WebP file and then plot into it. Ensure to call dev.off() to finalize the file. ```R file <- tempfile(fileext = '.webp') agg_webp(file) plot(sin, -pi, 2*pi) dev.off() #> agg_record_20e61a50bf8d #> 2 ``` -------------------------------- ### Create a PPM file and plot a sine wave Source: https://ragg.r-lib.org/reference/agg_ppm.html Example of using agg_ppm to create a PPM file, plotting a sine wave, and then closing the device. Ensure to call dev.off() to finalize the file. ```R file <- tempfile(fileext = '.ppm') agg_ppm(file) plot(sin, -pi, 2*pi) dev.off() #> agg_record_20e6541fc7b5 #> 2 ``` -------------------------------- ### Draw to a PNG file with agg_png Source: https://ragg.r-lib.org/reference/agg_png.html Example of using agg_png to create a PNG file. It sets up the device, plots a sine wave, and then closes the device. Ensure dev.off() is called to finalize the file. ```R file <- tempfile(fileext = '.png') agg_png(file) plot(sin, -pi, 2*pi) dev.off() #> agg_record_20e66cfe61f3 #> 2 ``` -------------------------------- ### Create and Save a JPEG Plot Source: https://ragg.r-lib.org/reference/agg_jpeg.html Example demonstrating how to create a JPEG file with specified quality and plot a sine wave to it. Ensure to close the device using dev.off() after plotting. ```R file <- tempfile(fileext = '.jpeg') agg_jpeg(file, quality = 50) plot(sin, -pi, 2*pi) dev.off() #> agg_record_20e6114e9f37 #> 2 ``` -------------------------------- ### Install Ragg Package Source: https://ragg.r-lib.org/index.html Install the ragg package from CRAN or the development version from GitHub using the pak package. ```R install.packages('pak') pak::pak('r-lib/ragg') ``` -------------------------------- ### Create animated WebP plot Source: https://ragg.r-lib.org/reference/agg_webp_anim.html Example of creating an animated WebP file. This code generates a temporary file, draws a series of sine wave plots with increasing phase, and saves the animation. Ensure `dev.flush()` is called after each plot update and `dev.off()` to finalize the file. ```R file <- tempfile(fileext = '.webp') agg_webp_anim(file, delay = 100, loop = 0) for(i in 1:10) { plot(sin(1:100 + i/10), type = 'l', ylim = c(-1, 1)) dev.flush() } de v.off() #> agg_record_20e627a3c558 #> 2 ``` -------------------------------- ### Create PNG Graphic with Ragg and ggplot2 Source: https://ragg.r-lib.org/index.html Generates a PNG file using agg_png and ggplot2, demonstrating custom font usage. This example requires the ggplot2 library and conditionally sets a font family based on the operating system. ```R library(ragg) library(ggplot2) file <- knitr::fig_path('.png') on_linux <- tolower(Sys.info()[['sysname']]) == 'linux' fancy_font <- if (on_linux) 'URW Chancery L' else 'Papyrus' agg_png(file, width = 1000, height = 500, res = 144) ggplot(mtcars) + geom_point(aes(mpg, disp, colour = hp)) + labs(title = 'System fonts — Oh My! 😱') + theme(text = element_text(family = fancy_font)) invisible(dev.off()) knitr::include_graphics(file) ``` -------------------------------- ### Test ragg Text Rendering (No Rotation) Source: https://ragg.r-lib.org/articles/ragg_quality.html Renders text using the ragg device without rotation. Ensure the 'ragg' package is installed and loaded. ```R ragg_text <- knitr::fig_path('.png') text_quality(agg_png, 'ragg', ragg_text) ``` ```R knitr::include_graphics(ragg_text) ``` -------------------------------- ### Benchmark Device Open/Close Performance Source: https://ragg.r-lib.org/articles/ragg_performance.html Compares the time taken to open, create a new plot, and close different PNG devices. This benchmark helps understand differences in buffer allocation and file serialization, potentially influenced by compression and filtering settings. ```r file <- tempfile(fileext = '.png') res <- bench::mark( ragg = {agg_png(file); plot.new(); dev.off()}, cairo = {png(file, type = 'cairo'); plot.new(); dev.off()}, cairo_png = {png(file, type = 'cairo-png'); plot.new(); dev.off()}, Xlib = if (has_xlib) {png(file, type = 'Xlib'); plot.new(); dev.off()} else NULL, check = FALSE ) if (!has_xlib) { res <- res[-4, ] attr(res$expression, 'description') <- attr(res$expression, 'description')[-4] } plot(res, type = 'ridge') + ggtitle('Open and close performance') ``` -------------------------------- ### Create and Render a Pattern Fill Source: https://ragg.r-lib.org/articles/ragg_performance.html Defines a pattern using segments and applies it to circle grobs, then benchmarks the rendering performance. ```R segments <- segmentsGrob(runif(1000), runif(1000), runif(1000), runif(1000), gp = gpar(col = sample(palette(), 1000, TRUE))) pat <- pattern(segments, width = 0.1, height = 0.1, extend = 'reflect') circles <- circleGrob(runif(1000), runif(1000), r = unit(1, 'char'), gp = gpar(fill = pat)) void_dev() plot.new() b <- system.time(grid.draw(circles)) invisible(dev.off()) res <- all_render_bench(grid.draw(circles)) plot_bench(res, 'Pattern performance', b) ``` -------------------------------- ### Initialize agg_capture device Source: https://ragg.r-lib.org/reference/agg_capture.html Defines the parameters for the agg_capture graphic device. ```R agg_capture( width = 480, height = 480, units = "px", pointsize = 12, background = "white", res = 72, scaling = 1, snap_rect = TRUE, bg ) ``` -------------------------------- ### Initialize agg_supertransparent device Source: https://ragg.r-lib.org/reference/agg_supertransparent.html Use this function to open a graphics device that supports 16bit color depth and alpha channel modification. ```R agg_supertransparent( filename = "Rplot%03d.png", width = 480, height = 480, units = "px", pointsize = 12, background = "white", res = 72, scaling = 1, snap_rect = TRUE, alpha_mod = 1, bg ) ``` -------------------------------- ### Capture Drawing Instructions with agg_record Source: https://ragg.r-lib.org/reference/agg_record.html Use `agg_record()` to create a graphics device that captures drawing instructions without rendering. This is useful for performance when only the instructions are needed. The function has several arguments to control the device's dimensions, units, pointsize, background color, resolution, and scaling. ```R agg_record( width = 480, height = 480, units = "px", pointsize = 12, background = "white", res = 72, scaling = 1, snap_rect = TRUE, bg ) ``` -------------------------------- ### agg_ppm Function Source: https://ragg.r-lib.org/reference/agg_ppm.html Initializes a graphics device that outputs to a PPM file. ```APIDOC ## agg_ppm ### Description Initializes a graphics device that renders R plots to a PPM (Portable Pixel Map) file. ### Method Function Call ### Parameters - **filename** (string) - Optional - The name of the file. Supports sprintf() compliant string formats for multiple plots. - **width** (numeric) - Optional - The width of the device. - **height** (numeric) - Optional - The height of the device. - **units** (string) - Optional - The unit for width and height ('px', 'in', 'mm', 'cm'). - **pointsize** (numeric) - Optional - The default pointsize of the device in pt. - **background** (string) - Optional - The background colour of the device. - **res** (numeric) - Optional - The resolution of the device. - **scaling** (numeric) - Optional - A scaling factor for line width and text size. - **snap_rect** (boolean) - Optional - Whether to snap axis-aligned rectangles to the pixel grid. - **bg** (string) - Optional - Alias for background. ### Request Example agg_ppm(filename = "plot.ppm", width = 800, height = 600) ### Response - **device** (object) - Returns an active graphics device. ``` -------------------------------- ### agg_record() - Capture drawing instructions Source: https://ragg.r-lib.org/reference/agg_record.html The `agg_record()` function creates a graphics device that captures drawing instructions without rendering them. This is useful for scenarios where you only need the instructions for later playback on another device, avoiding the performance overhead of actual rendering. ```APIDOC ## agg_record() ### Description Creates a graphics device that captures drawing instructions without rendering. This is a no-overhead solution for plot recording. ### Usage ```R agg_record( width = 480, height = 480, units = "px", pointsize = 12, background = "white", res = 72, scaling = 1, snap_rect = TRUE, bg ) ``` ### Arguments * **width** (numeric) - The width of the device. * **height** (numeric) - The height of the device. * **units** (character) - The unit `width` and `height` is measured in, in either pixels (`'px'`), inches (`'in'`), millimeters (`'mm'`), or centimeter (`'cm'`). * **pointsize** (numeric) - The default pointsize of the device in pt. This will in general not have any effect on grid graphics (including ggplot2) as text size is always set explicitly there. * **background** (character) - The background colour of the device. * **res** (numeric) - The resolution of the device. This setting will govern how device dimensions given in inches, centimeters, or millimeters will be converted to pixels. Further, it will be used to scale text sizes and linewidths. * **scaling** (numeric) - A scaling factor to apply to the rendered line width and text size. Useful for getting the right dimensions at the resolution that you need. * **snap_rect** (logical) - Should axis-aligned rectangles drawn with only fill snap to the pixel grid. This will prevent anti-aliasing artifacts when two rectangles are touching at their border. * **bg** (character) - Same as `background` for compatibility with old graphic device APIs. ### Examples ```R # Capture drawing instructions agg_record() plot(1:10, 1:10) rec <- recordPlot() dev.off() # Replay these on another device file <- tempfile(fileext = '.png') agg_png(file) replayPlot(rec) dev.off() ``` ``` -------------------------------- ### Render Circle with Cairo PNG Device (Grayscale Anti-aliasing) Source: https://ragg.r-lib.org/articles/ragg_quality.html Generates a PNG image of circles using the base R png device with Cairo backend, applying grayscale anti-aliasing. This is for quality comparison. ```R cairo_gray_circle <- knitr::fig_path('.png') circle_quality(png, 'cairo gray AA', cairo_gray_circle, type = 'cairo', antialias = 'gray') knitr::include_graphics(cairo_gray_circle) ``` -------------------------------- ### Render Circle with Cairo PNG Device (Subpixel Anti-aliasing) Source: https://ragg.r-lib.org/articles/ragg_quality.html Generates a PNG image of circles using the base R png device with Cairo backend, applying subpixel anti-aliasing. This is for quality comparison. ```R cairo_subpixel_circle <- knitr::fig_path('.png') circle_quality(png, 'cairo subpixel AA', cairo_subpixel_circle, type = 'cairo', antialias = 'subpixel') knitr::include_graphics(cairo_subpixel_circle) ``` -------------------------------- ### Define Benchmarking Utilities Source: https://ragg.r-lib.org/articles/ragg_performance.html Helper functions to execute performance benchmarks across different graphic devices and visualize the results using ridge plots. ```R render_bench <- function(dev_f, ...) { dots <- rlang::enexprs(...) force(dev_f) on.exit(dev.off()) plot.new() rlang::eval_tidy(expr(bench::mark(!!!dots, min_iterations = 10))) } all_render_bench <- function(expr, xlib = TRUE) { file <- tempfile() expr <- rlang::enexpr(expr) res <- list( render_bench(agg_png(file), ragg = !!expr), render_bench(png(file, type = "cairo", antialias = 'none'), cairo_none = !!expr), render_bench(png(file, type = "cairo", antialias = 'gray'), cairo_gray = !!expr), render_bench(png(file, type = "cairo", antialias = 'subpixel'), cairo_subpixel = !!expr), if (has_xlib && xlib) render_bench(png(file, type = "Xlib"), xlib = !!expr) else NULL ) expr <- unlist(lapply(res, `[[`, 'expression'), recursive = FALSE) res <- do.call(rbind, res) res$expression <- expr class(res$expression) <- c('bench_expr', 'expression') attr(res$expression, 'description') <- names(res$expression) res$Anti_aliased <- c(TRUE, FALSE, TRUE, TRUE, FALSE)[seq_len(nrow(res))] res } plot_bench <- function(x, title, baseline) { plot(x, type = 'ridge', aes(fill = Anti_aliased)) + facet_null() + geom_vline(xintercept = baseline['elapsed'], linetype = 2, colour = 'grey') + annotate('text', x = baseline['elapsed'], y = -Inf, label = ' baseline', vjust = 0, hjust = 0, colour = 'grey') + scale_fill_brewer(labels = c('No', 'Yes'), type = 'qual') + labs(title = title, fill = 'Anti-aliased', x = NULL, y = NULL) + theme_minimal() + theme(panel.grid.major.y = element_blank(), legend.position = 'bottom') + scale_x_continuous(labels = function(x) {format(bench:::as_bench_time(x))}) } ``` -------------------------------- ### Render Circle with Cairo PNG Device (No Anti-aliasing) Source: https://ragg.r-lib.org/articles/ragg_quality.html Generates a PNG image of circles using the base R png device with Cairo backend, specifically disabling anti-aliasing. This is for comparison purposes. ```R cairo_none_circle <- knitr::fig_path('.png') circle_quality(png, 'cairo no AA', cairo_none_circle, type = 'cairo', antialias = 'none') knitr::include_graphics(cairo_none_circle) ``` -------------------------------- ### Create and Render a Gradient Fill Source: https://ragg.r-lib.org/articles/ragg_performance.html Generates circle grobs filled with a linear gradient and measures rendering performance. ```R circles <- circleGrob(runif(2000), runif(2000), r = unit(0.5, 'char'), gp = gpar(fill = linearGradient(c('black', 'transparent', 'blue')))) void_dev() plot.new() b <- system.time(grid.draw(circles)) invisible(dev.off()) res <- all_render_bench(grid.draw(circles)) plot_bench(res, 'Gradient performance', b) ``` -------------------------------- ### Load Ragg and Supporting Libraries Source: https://ragg.r-lib.org/articles/ragg_performance.html Loads the necessary libraries for benchmarking ragg and ggplot2. ```r library(ragg) library(devoid) library(ggplot2) ``` -------------------------------- ### Test Cairo Text Rendering (27° Rotation, Gray AA) Source: https://ragg.r-lib.org/articles/ragg_quality.html Renders text using the base R png device with Cairo backend and grayscale anti-aliasing, with a 27-degree rotation. Observe how gray AA affects rotated text. ```R cairo_gray_text_rot <- knitr::fig_path('.png') text_quality(png, 'cairo gray AA', cairo_gray_text_rot, rotation = 27, type = 'cairo', antialias = 'gray') ``` ```R knitr::include_graphics(cairo_gray_text_rot) ``` -------------------------------- ### Create and Render a Mask with Performance Test Source: https://ragg.r-lib.org/articles/ragg_performance.html Defines a mask using random points and applies it to segments. Includes performance benchmarking for rendering. ```R mask <- pointsGrob(runif(2000), runif(2000), default.units = 'npc', pch = 16, gp = gpar(col = '#00000077')) segments <- segmentsGrob(runif(100), runif(100), runif(100), runif(100), vp = viewport(mask = mask)) void_dev() plot.new() b <- system.time(grid.draw(segments)) invisible(dev.off()) res <- all_render_bench(grid.draw(segments)) plot_bench(res, 'Complex mask performance', b) ``` -------------------------------- ### Test Cairo Text Rendering (No Rotation, No AA) Source: https://ragg.r-lib.org/articles/ragg_quality.html Renders text using the base R png device with Cairo backend and no anti-aliasing. This is useful for comparing raw rendering. ```R cairo_none_text <- knitr::fig_path('.png') text_quality(png, 'cairo no AA', cairo_none_text, type = 'cairo', antialias = 'none') ``` ```R knitr::include_graphics(cairo_none_text) ``` -------------------------------- ### Benchmark Polyline Performance Source: https://ragg.r-lib.org/articles/ragg_performance.html Performance comparison for connected lines and patterned polylines across graphic devices. ```R void_dev() plot.new() b <- system.time(lines(x, y)) invisible(dev.off()) res <- all_render_bench(lines(x, y)) plot_bench(res, 'Connected line performance', b) ``` ```R void_dev() plot.new() b <- system.time(lines(x, y, lty = 4)) invisible(dev.off()) res <- all_render_bench(lines(x, y, lty = 4)) plot_bench(res, 'Patterned connected line performance', b) ``` -------------------------------- ### Test Cairo Text Rendering (27° Rotation, No AA) Source: https://ragg.r-lib.org/articles/ragg_quality.html Renders text using the base R png device with Cairo backend and no anti-aliasing, with a 27-degree rotation. Note potential jaggedness in rotated text. ```R cairo_none_text_rot <- knitr::fig_path('.png') text_quality(png, 'cairo no AA', cairo_none_text_rot, rotation = 27, type = 'cairo', antialias = 'none') ``` ```R knitr::include_graphics(cairo_none_text_rot) ``` -------------------------------- ### Benchmark clipping path performance Source: https://ragg.r-lib.org/articles/ragg_performance.html Evaluates rendering performance when using arbitrary clipping paths defined by grid grobs. ```R library(grid) clip <- pointsGrob(runif(500), runif(500), default.units = 'npc') segments <- segmentsGrob(runif(100), runif(100), runif(100), runif(100), vp = viewport(clip = clip)) void_dev() plot.new() b <- system.time(grid.draw(segments)) invisible(dev.off()) res <- all_render_bench(grid.draw(segments)) plot_bench(res, 'Complex clip path performance', b) ``` -------------------------------- ### Image Cropping and Sampling Function Source: https://ragg.r-lib.org/articles/ragg_quality.html A utility function to read, crop, and sample an image. Requires the magick package. ```R library(ragg) library(grid) library(magick) img_zoom <- function(path) { img <- image_read(path) img <- image_crop(img, '300x150+150+75') img <- image_sample(img, '600x300') img } ``` -------------------------------- ### Test Cairo Text Rendering (27° Rotation, Subpixel AA) Source: https://ragg.r-lib.org/articles/ragg_quality.html Renders text using the base R png device with Cairo backend and subpixel anti-aliasing, with a 27-degree rotation. This demonstrates Cairo's subpixel rendering for rotated text. ```R cairo_subpixel_text_rot <- knitr::fig_path('.png') text_quality(png, 'cairo subpixel AA', cairo_subpixel_text_rot, rotation = 27, type = 'cairo', antialias = 'subpixel') ``` ```R knitr::include_graphics(cairo_subpixel_text_rot) ``` -------------------------------- ### Test Cairo Text Rendering (No Rotation, Subpixel AA) Source: https://ragg.r-lib.org/articles/ragg_quality.html Renders text using the base R png device with Cairo backend and subpixel anti-aliasing. This is often considered the highest quality for screen rendering. ```R cairo_subpixel_text <- knitr::fig_path('.png') text_quality(png, 'cairo subpixel AA', cairo_subpixel_text, type = 'cairo', antialias = 'subpixel') ``` ```R knitr::include_graphics(cairo_subpixel_text) ``` -------------------------------- ### Benchmark complex graphic rendering Source: https://ragg.r-lib.org/articles/ragg_performance.html Measures the rendering time of a prebuilt ggplot2 grob using the all_render_bench utility. ```R p <- ggplotGrob(p) void_dev() b <- system.time(plot(p)) invisible(dev.off()) res <- all_render_bench(plot(p)) plot_bench(res, 'Complex composite performance', b) ``` -------------------------------- ### Test Cairo Text Rendering (No Rotation, Gray AA) Source: https://ragg.r-lib.org/articles/ragg_quality.html Renders text using the base R png device with Cairo backend and grayscale anti-aliasing. This tests Cairo's default font rendering quality. ```R cairo_gray_text <- knitr::fig_path('.png') text_quality(png, 'cairo gray AA', cairo_gray_text, type = 'cairo', antialias = 'gray') ``` ```R knitr::include_graphics(cairo_gray_text) ``` -------------------------------- ### Benchmark Text String Performance Source: https://ragg.r-lib.org/articles/ragg_performance.html Measures the performance of rendering text strings. Requires 'x' and 'y' coordinates and a 'label' string to be defined. ```R void_dev() plot.new() b <- system.time(text(x, y, label = 'abcdefghijk')) invisible(dev.off()) res <- all_render_bench(text(x, y, label = 'abcdefghijk')) plot_bench(res, 'Text string performance', b) ``` -------------------------------- ### agg_png Function Source: https://ragg.r-lib.org/reference/agg_png.html Initializes a new PNG graphics device for rendering plots. ```APIDOC ## agg_png ### Description Initializes a PNG graphics device. Unlike grDevices::png(), this function does not write date/time metadata to the file, ensuring deterministic output. ### Parameters - **filename** (string) - Optional - The name of the file. Supports sprintf() formatting. - **width** (numeric) - Optional - The width of the device. - **height** (numeric) - Optional - The height of the device. - **units** (string) - Optional - Units for width/height ('px', 'in', 'mm', 'cm'). - **pointsize** (numeric) - Optional - Default pointsize in pt. - **background** (string) - Optional - Background color. - **res** (numeric) - Optional - Resolution of the device. - **scaling** (numeric) - Optional - Scaling factor for line width and text size. - **snap_rect** (boolean) - Optional - Whether to snap axis-aligned rectangles to the pixel grid. - **bitsize** (numeric) - Optional - Color depth (8 or 16). - **bg** (string) - Optional - Alias for background. ### Request Example agg_png(filename = "plot.png", width = 800, height = 600, res = 300) ### Response - **device** (object) - Returns a graphics device connection that must be closed with dev.off(). ``` -------------------------------- ### Benchmark Path Rendering Performance Source: https://ragg.r-lib.org/articles/ragg_performance.html Benchmarks complex path rendering using the polypath function, noting that Xlib does not support this feature. ```R section <- rep(1:10, each = 100) x_path <- unlist(lapply(split(x, section), function(x) c(x, NA))) y_path <- unlist(lapply(split(y, section), function(x) c(x, NA))) x_path <- x_path[-length(x_path)] y_path <- y_path[-length(y_path)] void_dev() plot.new() b <- system.time(polypath(x_path, y_path, rule = 'evenodd')) invisible(dev.off()) res <- all_render_bench(polypath(x_path, y_path, rule = 'evenodd'), xlib = FALSE) plot_bench(res, 'Unfilled path performance', b) ``` ```R void_dev() plot.new() b <- system.time(polypath(x_path, y_path, rule = 'evenodd', border = 'gray', col = 'black')) invisible(dev.off()) res <- all_render_bench(polypath(x_path, y_path, rule = 'evenodd', border = 'gray', col = 'black'), xlib = FALSE) plot_bench(res, 'Filled path performance', b) ``` -------------------------------- ### Benchmark Circle Drawing Performance Source: https://ragg.r-lib.org/articles/ragg_performance.html Performance comparison for drawing unfilled and filled circles using different graphic devices. ```R x <- runif(1000) y <- runif(1000) pch <- 1 void_dev() plot.new() b <- system.time(points(x, y, pch = pch)) invisible(dev.off()) res <- all_render_bench(points(x, y, pch = pch)) plot_bench(res, 'Unfilled circle performance', b) ``` ```R pch <- 19 void_dev() plot.new() b <- system.time(points(x, y, pch = pch)) invisible(dev.off()) res <- all_render_bench(points(x, y, pch = pch)) plot_bench(res, 'Filled circle performance', b) ``` -------------------------------- ### agg_tiff Function Source: https://ragg.r-lib.org/reference/agg_tiff.html Initializes a graphics device that records plots to a TIFF file. ```APIDOC ## agg_tiff ### Description Initializes a graphics device for rendering R plots to a TIFF file. Supports 8 and 16-bit color modes, transparency, and various compression algorithms. ### Parameters - **filename** (string) - Optional - The name of the file. Supports sprintf-style formatting for multiple plots. - **width** (numeric) - Optional - The width of the device. - **height** (numeric) - Optional - The height of the device. - **units** (string) - Optional - Units for dimensions: 'px', 'in', 'mm', or 'cm'. - **pointsize** (numeric) - Optional - Default pointsize in pt. - **background** (string) - Optional - Background color. - **res** (numeric) - Optional - Resolution in PPI. - **scaling** (numeric) - Optional - Scaling factor for line width and text size. - **snap_rect** (boolean) - Optional - Whether to snap axis-aligned rectangles to the pixel grid. - **compression** (string) - Optional - Compression type (e.g., 'none', 'lzw+p'). - **bitsize** (numeric) - Optional - Color depth: 8 or 16. ### Request Example agg_tiff(filename = "plot.tiff", width = 800, height = 600, compression = "lzw+p") ### Response - **device** (object) - Returns an active graphics device connection. ``` -------------------------------- ### Capture and process buffer data Source: https://ragg.r-lib.org/reference/agg_capture.html Demonstrates capturing plot data as a matrix or nativeRaster and visualizing the result. ```R cap <- agg_capture() plot(1:10, 1:10) # Get the plot as a matrix raster <- cap() # Get the plot as a nativeRaster raster_n <- cap(native = TRUE) dev.off() #> agg_record_20e62ddb38a6 #> 2 # Look at the output plot(as.raster(raster)) ``` -------------------------------- ### Render Circle with Ragg PNG Device Source: https://ragg.r-lib.org/articles/ragg_quality.html Generates a PNG image of circles using the ragg device for quality assessment. The output file path is determined by knitr::fig_path. ```R ragg_circle <- knitr::fig_path('.png') circle_quality(agg_png, 'ragg', ragg_circle) knitr::include_graphics(ragg_circle) ``` -------------------------------- ### Define agg_tiff device parameters Source: https://ragg.r-lib.org/reference/agg_tiff.html The function signature for configuring the TIFF graphics device, including dimensions, resolution, and compression settings. ```R agg_tiff( filename = "Rplot%03d.tiff", width = 480, height = 480, units = "px", pointsize = 12, background = "white", res = 72, scaling = 1, snap_rect = TRUE, compression = "none", bitsize = 8, bg ) ``` -------------------------------- ### Circle Rendering Function for Quality Comparison Source: https://ragg.r-lib.org/articles/ragg_quality.html A function to draw circles for comparing rendering quality across different devices. It sets up a graphics device, draws circles with specified properties, adds text, and then closes the device. ```R circle_quality <- function(device, name, file, ...) { device(file, width = 600, height = 300, ...) grid.circle( x = c(0.25, 0.75), r = 0.4, gp = gpar(col = c('black', NA), fill = c(NA, 'black'), lwd = 2) ) grid.text(y = 0.1, label = name, gp = gpar(cex = 2)) invisible(dev.off()) } ``` -------------------------------- ### agg_capture Function Source: https://ragg.r-lib.org/reference/agg_capture.html The agg_capture device creates a graphics device that captures output into a buffer, returning a function to access the image data. ```APIDOC ## agg_capture() ### Description Usually the point of using a graphic device is to create a file or show the graphic on the screen. A few times we need the image data for further processing in R, and instead of writing it to a file and then reading it back into R the `agg_capture()` device lets you get the image data directly from the buffer. In contrast to the other devices this device returns a function, that when called will return the current state of the buffer. ### Method Not applicable (R function) ### Endpoint Not applicable (R function) ### Parameters #### Arguments - **width** (numeric) - The width of the device. - **height** (numeric) - The height of the device. - **units** (character) - The unit `width` and `height` is measured in, in either pixels (`'px'`), inches (`'in'`), millimeters (`'mm'`), or centimeter (`'cm'`). - **pointsize** (numeric) - The default pointsize of the device in pt. This will in general not have any effect on grid graphics (including ggplot2) as text size is always set explicitly there. - **background** (character) - The background colour of the device. - **res** (numeric) - The resolution of the device. This setting will govern how device dimensions given in inches, centimeters, or millimeters will be converted to pixels. Further, it will be used to scale text sizes and linewidths. - **scaling** (numeric) - A scaling factor to apply to the rendered line width and text size. Useful for getting the right dimensions at the resolution that you need. If e.g. you need to render a plot at 4000x3000 pixels for it to fit into a layout, but you find that the result appears to small, you can increase the `scaling` argument to make everything appear bigger at the same resolution. - **snap_rect** (logical) - Should axis-aligned rectangles drawn with only fill snap to the pixel grid. This will prevent anti-aliasing artifacts when two rectangles are touching at their border. - **bg** (character) - Same as `background` for compatibility with old graphic device APIs. ### Value A function that when called returns the current state of the buffer. The return value of the function depends on the `native` argument. If `FALSE` (default) the return value is a `matrix` of colour values and if `TRUE` the return value is a `nativeRaster` object. ### Examples ```R cap <- agg_capture() plot(1:10, 1:10) # Get the plot as a matrix raster <- cap() # Get the plot as a nativeRaster raster_n <- cap(native = TRUE) dev.off() # Look at the output plot(as.raster(raster)) ``` ``` -------------------------------- ### agg_webp function signature Source: https://ragg.r-lib.org/reference/agg_webp.html Defines the parameters for creating a WebP file. Supports custom filenames, dimensions, units, background color, resolution, scaling, and compression settings (lossy/lossless, quality). ```R agg_webp( filename = "Rplot%03d.webp", width = 480, height = 480, units = "px", pointsize = 12, background = "white", res = 72, scaling = 1, snap_rect = TRUE, lossy = FALSE, quality = 80, bg ) ``` -------------------------------- ### agg_webp_anim function signature Source: https://ragg.r-lib.org/reference/agg_webp_anim.html Defines the parameters for creating an animated WebP file. Use this function to specify output filename, dimensions, resolution, compression quality, and animation timing. ```R agg_webp_anim( filename = "Ranim.webp", width = 480, height = 480, units = "px", pointsize = 12, background = "white", res = 72, scaling = 1, snap_rect = TRUE, lossy = FALSE, quality = 80, delay = 100L, loop = 0L, bg ) ``` -------------------------------- ### Test ragg Text Rendering (27° Rotation) Source: https://ragg.r-lib.org/articles/ragg_quality.html Renders text using the ragg device with a 27-degree counter-clockwise rotation. This demonstrates ragg's handling of rotated text. ```R ragg_text_rot <- knitr::fig_path('.png') text_quality(agg_png, 'ragg', ragg_text_rot, rotation = 27) ``` ```R knitr::include_graphics(ragg_text_rot) ``` -------------------------------- ### Benchmark Rectangle Rendering Performance Source: https://ragg.r-lib.org/articles/ragg_performance.html Measures rendering time for unfilled and filled rectangles using the points function with different pch values. ```R pch <- 0 void_dev() plot.new() b <- system.time(points(x, y, pch = pch)) invisible(dev.off()) res <- all_render_bench(points(x, y, pch = pch)) plot_bench(res, 'Unfilled rectangle performance', b) ``` ```R pch <- 15 void_dev() plot.new() b <- system.time(points(x, y, pch = pch)) invisible(dev.off()) res <- all_render_bench(points(x, y, pch = pch)) plot_bench(res, 'Filled rectangle performance', b) ``` -------------------------------- ### Configure knitr to Use Ragg PNG Device Source: https://ragg.r-lib.org/index.html Set the default graphics device for knitr to 'ragg_png' either globally or within a specific chunk for PNG output. ```R knitr::opts_chunk$set(dev = "ragg_png") ``` -------------------------------- ### agg_webp Function Reference Source: https://ragg.r-lib.org/reference/agg_webp.html Reference for the agg_webp function, used to create WebP graphics devices. ```APIDOC ## agg_webp ### Description Draws to a WebP file. The WebP format is a raster image format that provides improved lossless (and lossy) compression for images on the web. Transparency is supported. ### Usage ```R agg_webp( filename = "Rplot%03d.webp", width = 480, height = 480, units = "px", pointsize = 12, background = "white", res = 72, scaling = 1, snap_rect = TRUE, lossy = FALSE, quality = 80, bg ) ``` ### Arguments - **filename** (character) - The name of the file. Follows the same semantics as the file naming in `grDevices::png()`, meaning that you can provide a `sprintf()` compliant string format to name multiple plots (such as the default value). - **width** (numeric) - The dimensions of the device. - **height** (numeric) - The dimensions of the device. - **units** (character) - The unit `width` and `height` is measured in, in either pixels (`'px'`), inches (`'in'`), millimeters (`'mm'`), or centimeter (`'cm'`). - **pointsize** (numeric) - The default pointsize of the device in pt. This will in general not have any effect on grid graphics (including ggplot2) as text size is always set explicitly there. - **background** (character) - The background colour of the device. - **res** (numeric) - The resolution of the device. This setting will govern how device dimensions given in inches, centimeters, or millimeters will be converted to pixels. Further, it will be used to scale text sizes and linewidths. - **scaling** (numeric) - A scaling factor to apply to the rendered line width and text size. Useful for getting the right dimensions at the resolution that you need. If e.g. you need to render a plot at 4000x3000 pixels for it to fit into a layout, but you find that the result appears to small, you can increase the `scaling` argument to make everything appear bigger at the same resolution. - **snap_rect** (logical) - Should axis-aligned rectangles drawn with only fill snap to the pixel grid. This will prevent anti-aliasing artifacts when two rectangles are touching at their border. - **lossy** (logical) - Use lossy compression. Default is `FALSE`. - **quality** (integer) - An integer between `0` and `100` defining either the quality (if using lossy compression) or the compression effort (if using lossless). - **bg** (character) - Same as `background` for compatibility with old graphic device APIs. ### Examples ```R file <- tempfile(fileext = '.webp') agg_webp(file) plot(sin, -pi, 2*pi) dev.off() ``` ``` -------------------------------- ### Graphic Device Functions Source: https://ragg.r-lib.org/reference/index.html Overview of the available graphic device functions in the ragg package for rendering and capturing graphics. ```APIDOC ## Graphic Device Functions ### Description The ragg package provides several graphic devices that share the same underlying rendering engine, differing only in their output format or destination. ### Available Functions - **agg_png()**: Draw to a PNG file. - **agg_jpeg()**: Draw to a JPEG file. - **agg_tiff()**: Draw to a TIFF file. - **agg_webp()**: Draw to a WebP file. - **agg_webp_anim()**: Draw an animation to a WebP file. - **agg_capture()**: Draw to a buffer that can be accessed directly. - **agg_ppm()**: Draw to a PPM file. - **agg_record()**: Capture drawing instructions without rendering. ``` -------------------------------- ### Benchmark Polygon Rendering Performance Source: https://ragg.r-lib.org/articles/ragg_performance.html Evaluates performance for simple points-based polygons and complex filled or unfilled polygons using the polygon function. ```R pch <- 2 void_dev() plot.new() b <- system.time(points(x, y, pch = pch)) invisible(dev.off()) res <- all_render_bench(points(x, y, pch = pch)) plot_bench(res, 'Simple polygon performance', b) ``` ```R void_dev() plot.new() b <- system.time(polygon(x, y)) invisible(dev.off()) res <- all_render_bench(polygon(x, y)) plot_bench(res, 'Unfilled complex polygon performance', b) ``` ```R void_dev() plot.new() b <- system.time(polygon(x, y, border = 'gray', col = 'black')) invisible(dev.off()) res <- all_render_bench(polygon(x, y, border = 'gray', col = 'black')) plot_bench(res, 'Filled complex polygon performance', b) ``` -------------------------------- ### Define Text Quality Testing Function Source: https://ragg.r-lib.org/articles/ragg_quality.html A function to test text rendering quality at various sizes and rotations. It requires a device function, a name, a file path, and an optional rotation angle. ```R text_quality <- function(device, name, file, rotation = 0, ...) { text <- 'The quick blue R jumped over the lazy snake' vp <- viewport(angle = rotation) device(file, width = 600, height = 300, ...) pushViewport(vp) grid.text(text, x = 0.1, y = 0.2, just = 'left', gp = gpar(fontfamily = 'serif', cex = 0.5)) grid.text(text, x = 0.1, y = 0.4, just = 'left', gp = gpar(fontfamily = 'serif', cex = 1)) grid.text(text, x = 0.1, y = 0.6, just = 'left', gp = gpar(fontfamily = 'serif', cex = 1.5)) grid.text(text, x = 0.1, y = 0.8, just = 'left', gp = gpar(fontfamily = 'serif', cex = 2)) popViewport() grid.text(x = 0.9, y = 0.1, label = name, just = 'right', gp = gpar(cex = 2)) invisible(dev.off()) } ``` -------------------------------- ### Create complex ggplot2 graphic Source: https://ragg.r-lib.org/articles/ragg_performance.html Constructs a multi-layered ggplot2 object using the diamonds dataset for performance testing. ```R p <- ggplot(diamonds, aes(carat, price)) + geom_hex() + geom_point(shape = 1, size = 0.05, colour = 'white') + geom_smooth() + facet_wrap(~clarity) + labs(title = '5 things you didn\'t knew about the diamonds dataset', subtitle = 'You won\'t believe number 4', caption = 'Source: The ggplot2 package') p ``` -------------------------------- ### agg_ppm function signature Source: https://ragg.r-lib.org/reference/agg_ppm.html Defines the parameters for creating a PPM device. The filename can use sprintf-style formatting for multiple plots. Units can be pixels, inches, millimeters, or centimeters. Scaling affects line width and text size. ```R agg_ppm( filename = "Rplot%03d.ppm", width = 480, height = 480, units = "px", pointsize = 12, background = "white", res = 72, scaling = 1, snap_rect = TRUE, bg ) ``` -------------------------------- ### BibTeX Citation for ragg Package Source: https://ragg.r-lib.org/authors.html Use this BibTeX entry for citing the ragg package in academic work. It includes author, title, year, version, and URL. ```bibtex @Manual{ title = {ragg: Graphic Devices Based on AGG}, author = {Thomas Lin Pedersen and Maxim Shemanarev}, year = {2026}, note = {R package version 1.5.2}, url = {https://ragg.r-lib.org}, } ```