### Install svglite Development Version Source: https://github.com/r-lib/svglite/blob/main/README.md Install the development version of svglite from GitHub using the pak package manager. ```r # install.packages("pak") pak::pak("r-lib/svglite") ``` -------------------------------- ### Configure Makevars for libpng on macOS (arm64) Source: https://github.com/r-lib/svglite/blob/main/README.md Example Makevars configuration for building svglite on macOS with arm64 architecture, ensuring libpng include and library paths are correctly set. ```mk CPPFLAGS += -I/opt/homebrew/include LDFLAGS += -L/opt/homebrew/lib ``` -------------------------------- ### Parse SVG as XML Document Source: https://context7.com/r-lib/svglite/llms.txt Demonstrates parsing an SVG generated by xmlSVG into an XML document for inspection and modification using the xml2 package. Requires xml2 to be installed. ```r if (require("xml2")) { # Create SVG and parse as XML x <- xmlSVG( plot(1:5, 1:5, type = "b", main = "Test Plot"), width = 7, height = 7, standalone = FALSE ) # Inspect the XML structure print(x) # Find all text elements text_nodes <- xml_find_all(x, ".//text") print(text_nodes) # Extract text content sapply(text_nodes, xml_text) # Find specific elements circles <- xml_find_all(x, ".//circle") lines <- xml_find_all(x, ".//line") # Modify SVG attributes xml_set_attr(xml_find_first(x, "//svg"), "class", "my-custom-class") # Save modified SVG write_xml(x, "modified_plot.svg") } ``` -------------------------------- ### xmlSVG: Get SVG as xml2 Document Source: https://context7.com/r-lib/svglite/llms.txt Runs plotting code and returns the SVG output as an xml2 document object. This allows for programmatic manipulation and inspection of the SVG structure. ```APIDOC ## xmlSVG ### Description Runs plotting code and returns the SVG as an xml2 document object for programmatic manipulation. Useful for post-processing, testing, and extracting SVG elements. ### Method `xmlSVG()` ### Parameters #### Path Parameters - **plot_code** (expression) - The R code that generates the plot. - **width** (numeric) - Width of the SVG in inches. Defaults to 7. - **height** (numeric) - Height of the SVG in inches. Defaults to 7. - **bg** (character) - Background color of the SVG. Defaults to "transparent". - **pointsize** (numeric) - Default point size in points. Defaults to 12. - **standalone** (logical) - If TRUE, includes the XML header. Defaults to TRUE. - **fix_text_size** (logical) - If TRUE, attempts to fix text width across renderers. Defaults to FALSE. - **scaling** (numeric) - A scaling factor for line widths and text sizes. Defaults to 1. - **id** (character) - An SVG ID to assign to the root `` element, useful for embedding. ### Request Example ```r library(svglite) library(xml2) # Generate SVG and get it as an xml2 document svg_doc <- xmlSVG({ plot(1:5, main = "XML SVG Example") points(3, 4, pch = 19, col = "blue") }) # Inspect the SVG document (e.g., get the title) title_element <- xml_find_first(svg_doc, "//title") if (!is.null(title_element)) { print(xml_text(title_element)) } # You can also save the document to a file # write_xml(svg_doc, "output.svg") ``` ### Response Returns an `xml_document` object from the `xml2` package, representing the generated SVG. ``` -------------------------------- ### Generate Compressed SVGZ Output with svglite Source: https://github.com/r-lib/svglite/blob/main/README.md Demonstrates how to create a compressed SVGZ file directly using svglite by providing a path with a ".svgz" extension. This results in a much smaller file size. ```r tmp3 <- tempfile(fileext = ".svgz") svglite(tmp3) plot(x, y) invisible(dev.off()) # svglite - svgz fs::file_size(tmp3) #> 9.45K ``` -------------------------------- ### Compare svglite and svg File Sizes Source: https://github.com/r-lib/svglite/blob/main/README.md Compares the file sizes of SVGs generated by svglite() and svg(). svglite() produces significantly smaller files. ```r # svglite fs::file_size(tmp1) #> 75K # svg fs::file_size(tmp2) #> 327K ``` -------------------------------- ### Handle Missing System Font Source: https://github.com/r-lib/svglite/blob/main/tests/testthat/_snaps/text-fonts.md Illustrates the warning issued by `validate_aliases` when a specified system font is not found, and shows the fallback font used. ```R validate_aliases(list(sans = "foobar"), list()) ``` -------------------------------- ### Benchmark svglite vs svg Speed Source: https://github.com/r-lib/svglite/blob/main/README.md Compares the rendering speed of svglite() against the built-in svg() device using a benchmark. svglite() is shown to be considerably faster. ```r library(svglite) x <- runif(1e3) y <- runif(1e3) tmp1 <- tempfile() tmp2 <- tempfile() svglite_test <- function() { svglite(tmp1) plot(x, y) dev.off() } svg_test <- function() { svg(tmp2, onefile = TRUE) plot(x, y) dev.off() } bench::mark(svglite_test(), svg_test(), min_iterations = 250, check = FALSE) #> # A tibble: 2 × 6 #> expression min median `itr/sec` mem_alloc `gc/sec` #> #> 1 svglite_test() 2.86ms 2.97ms 325. 709KB 5.28 #> 2 svg_test() 6.11ms 6.26ms 159. 224KB 0.638 ``` -------------------------------- ### Create SVG file with svglite Source: https://context7.com/r-lib/svglite/llms.txt Use svglite to save plots to an SVG file. Supports custom dimensions, background color, font settings, and scaling. Can create compressed .svgz files and multi-page output. ```r library(svglite) # Basic usage - save plot to SVG file svglite("my_plot.svg") plot(1:11, (-5:5)^2, type = "b", main = "Simple Example") dev.off() ``` ```r # Custom dimensions and settings svglite( filename = "custom_plot.svg", width = 12, # Width in inches height = 6, # Height in inches bg = "#f5f5f5", # Background color pointsize = 14, # Default point size standalone = TRUE, # Include XML header fix_text_size = TRUE, # Fix text width across renderers scaling = 1.5 # Scale line width and text ) plot(cars, main = "Speed vs Distance") abline(lm(dist ~ speed, data = cars), col = "red", lwd = 2) dev.off() ``` ```r # Create compressed SVG (svgz format) svglite("compressed_plot.svgz") hist(rnorm(1000), main = "Normal Distribution", col = "steelblue") dev.off() ``` ```r # Multi-page output with pattern svglite("page_%03d.svg") # Creates page_001.svg, page_002.svg, etc. for (i in 1:3) { plot(rnorm(100), main = paste("Plot", i)) } dev.off() ``` ```r # With custom SVG ID for embedding in HTML svglite("embedded.svg", id = "my-svg-chart") barplot(1:5, names.arg = LETTERS[1:5]) dev.off() ``` -------------------------------- ### Create Font Feature Specification with svglite Source: https://context7.com/r-lib/svglite/llms.txt Creates a font feature specification object for OpenType features. This object can be used with `register_variant`. ```r library(svglite) # Create font feature specification features <- font_feature( liga = TRUE, # Standard ligatures tnum = TRUE, # Tabular numbers kern = TRUE # Kerning ) # Use with register_variant register_variant( name = "Numbers Table", family = "Arial", features = font_feature(tnum = TRUE) ) ``` -------------------------------- ### svglite: Create SVG File Source: https://context7.com/r-lib/svglite/llms.txt The primary function to create an SVG graphics device that writes output to a file. It supports various customization options for dimensions, background, fonts, and scaling, as well as multi-page output and gzip compression. ```APIDOC ## svglite ### Description Creates an SVG graphics device writing output to a file. Produces W3C-compliant SVG with configurable dimensions, background color, font settings, and scaling options. Supports multi-page output with filename patterns and optional gzip compression for `.svgz` files. ### Method `svglite()` ### Parameters #### Path Parameters - **filename** (character) - The name of the SVG file to create. Can include a pattern for multi-page output (e.g., "page_%03d.svg"). - **width** (numeric) - Width of the SVG in inches. Defaults to 7. - **height** (numeric) - Height of the SVG in inches. Defaults to 7. - **bg** (character) - Background color of the SVG. Defaults to "transparent". - **pointsize** (numeric) - Default point size in points. Defaults to 12. - **standalone** (logical) - If TRUE, includes the XML header. Defaults to TRUE. - **fix_text_size** (logical) - If TRUE, attempts to fix text width across renderers. Defaults to FALSE. - **scaling** (numeric) - A scaling factor for line widths and text sizes. Defaults to 1. - **id** (character) - An SVG ID to assign to the root `` element, useful for embedding. ### Request Example ```r library(svglite) # Basic usage - save plot to SVG file svglite("my_plot.svg") plot(1:11, (-5:5)^2, type = "b", main = "Simple Example") dev.off() # Custom dimensions and settings svglite( filename = "custom_plot.svg", width = 12, # Width in inches height = 6, # Height in inches bg = "#f5f5f5", # Background color pointsize = 14, # Default point size standalone = TRUE, # Include XML header fix_text_size = TRUE, # Fix text width across renderers scaling = 1.5 # Scale line width and text ) plot(cars, main = "Speed vs Distance") abline(lm(dist ~ speed, data = cars), col = "red", lwd = 2) dev.off() # Create compressed SVG (svgz format) svglite("compressed_plot.svgz") hist(rnorm(1000), main = "Normal Distribution", col = "steelblue") dev.off() # Multi-page output with pattern svglite("page_%03d.svg") # Creates page_001.svg, page_002.svg, etc. for (i in 1:3) { plot(rnorm(100), main = paste("Plot", i)) } dev.off() # With custom SVG ID for embedding in HTML svglite("embedded.svg", id = "my-svg-chart") barplot(1:5, names.arg = LETTERS[1:5]) dev.off() ``` ### Response This function does not return a value directly but creates an SVG file on disk. The `dev.off()` call finalizes the file writing. ``` -------------------------------- ### Convert SVG to SVGZ with svglite Source: https://context7.com/r-lib/svglite/llms.txt Converts an existing SVG file to the compressed SVGZ format, overwriting the original. This significantly reduces file size for large visualizations. ```r library(svglite) # Create regular SVG first svglite("large_plot.svg") plot(rnorm(10000), rnorm(10000), pch = ".", main = "Large Dataset") dev.off() # Check original file size file.size("large_plot.svg") # e.g., 1500000 bytes # Convert to compressed SVGZ create_svgz("large_plot.svg") # Check compressed size (typically 70-90% smaller) file.size("large_plot.svg") # e.g., 200000 bytes # Alternative: Create SVGZ directly with svglite svglite("direct_compressed.svgz") # .svgz extension triggers compression plot(volcano) dev.off() ``` -------------------------------- ### Generate CSS @import for Web Fonts with svglite Source: https://context7.com/r-lib/svglite/llms.txt Generates `@import` CSS statements for web fonts, which can be included in SVG files for web deployment. This ensures consistent font rendering across different platforms. ```r library(svglite) # Generate @import statement for Google Fonts import_statement <- fonts_as_import("Roboto") print(import_statement) # Use generated import in svglite svglite("google_fonts.svg", web_fonts = list( fonts_as_import("Open Sans"), fonts_as_import("Roboto Mono") )) plot(1:10, main = "Google Fonts Plot") dev.off() ``` -------------------------------- ### Create @font-face CSS Specification with font_face Source: https://context7.com/r-lib/svglite/llms.txt Generates a @font-face CSS specification for embedding web fonts in SVG. Use with the web_fonts argument of svglite() or stringSVG(). Supports various font formats (ttf, woff2, woff, otf) and local fallbacks. Can embed font data directly. ```r library(svglite) # Create @font-face specification my_font <- font_face( family = "MyHelvetica", ttf = "https://example.com/fonts/MgOpenModernaBold.ttf", local = c("Helvetica Neue Bold", "HelveticaNeue-Bold"), weight = "bold", style = "normal" ) # Print the generated CSS print(my_font) # Output: # @font-face { # font-family: "MyHelvetica"; # src: local("Helvetica Neue Bold"), # local("HelveticaNeue-Bold"), # url("https://example.com/fonts/MgOpenModernaBold.ttf") format("truetype"); # font-weight: bold; # font-style: normal; # } # Use web fonts in SVG svglite( "webfont_plot.svg", web_fonts = list( # Using font_face specification font_face( family = "Roboto", woff2 = "https://fonts.example.com/roboto.woff2", woff = "https://fonts.example.com/roboto.woff", weight = "400" ), # Using Google Fonts @import URL "https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;700" ) ) par(family = "Roboto") plot(1:10, main = "Plot with Web Fonts") dev.off() # Font face with multiple formats for browser compatibility comprehensive_font <- font_face( family = "CustomFont", woff2 = "fonts/custom.woff2", woff = "fonts/custom.woff", ttf = "fonts/custom.ttf", otf = "fonts/custom.otf", local = "Custom Font Regular", weight = "400", style = "normal", stretch = "normal", range = "U+0000-00FF" # Basic Latin unicode range ) # Embed font data directly in SVG (increases file size but ensures portability) embedded_font <- font_face( family = "EmbeddedFont", ttf = "/path/to/local/font.ttf", embed = TRUE # Base64 encode font data into SVG ) ``` -------------------------------- ### Generate SVG string with svgstring Source: https://context7.com/r-lib/svglite/llms.txt Use svgstring to capture SVG output as a string, useful for dynamic web applications. Allows progressive building of SVG content. ```r library(svglite) # Basic usage - get SVG as string s <- svgstring(width = 8, height = 6) plot(rnorm(100), rnorm(100), main = "Scatter Plot", xlab = "X values", ylab = "Y values", pch = 19, col = rgb(0.2, 0.4, 0.8, 0.6)) dev.off() # Get the SVG content svg_content <- s() cat(substr(svg_content, 1, 500)) # Print first 500 characters ``` ```r # Progressive SVG building - check content during drawing s <- svgstring() s() # Empty SVG at start plot.new() s() # SVG with empty plot area text(0.5, 0.5, "Hello, SVG!") s() # SVG with text added dev.off() # Final complete SVG final_svg <- s() ``` ```r # Use in Shiny or web context # server <- function(input, output) { # output$plot <- renderUI({ # s <- svgstring(width = 10, height = 8) # plot(input$data) # dev.off() # HTML(s()) # }) # } ``` -------------------------------- ### Add Web Fonts to SVG Files or Strings with add_web_fonts Source: https://context7.com/r-lib/svglite/llms.txt Adds web font imports to existing SVG files or inline SVG strings after creation. This allows for post-hoc font specification without regenerating the plot. Supports adding fonts to multiple files at once. ```r library(svglite) # Create SVG without web fonts svglite("plot_no_fonts.svg") par(family = "sans") plot(1:10, main = "My Plot Title") text(5, 5, "Important Label", cex = 1.5) dev.off() # Add web fonts after creation add_web_fonts( "plot_no_fonts.svg", web_fonts = list( "https://fonts.googleapis.com/css2?family=Roboto:wght@400;700", font_face( family = "Arial", woff2 = "https://example.com/arial.woff2" ) ) ) # Add fonts to inline SVG string svg_str <- stringSVG(plot(cars, main = "Cars")) svg_with_fonts <- add_web_fonts( svg_str, web_fonts = list("https://fonts.googleapis.com/css2?family=Lato") ) # Add fonts to multiple files at once svg_files <- c("plot1.svg", "plot2.svg", "plot3.svg") add_web_fonts(svg_files, web_fonts = list( "https://fonts.googleapis.com/css2?family=Source+Sans+Pro" )) ``` -------------------------------- ### Register Font with svglite Source: https://context7.com/r-lib/svglite/llms.txt Registers a custom font file for use in plots. Ensure the font files exist at the specified paths. ```r library(svglite) # Register a custom font from file register_font( name = "MyCustomFont", plain = "/path/to/font-regular.ttf", bold = "/path/to/font-bold.ttf", italic = "/path/to/font-italic.ttf", bolditalic = "/path/to/font-bolditalic.ttf" ) # Use the registered font svglite("custom_font_plot.svg") par(family = "MyCustomFont") plot(1:10, main = "Custom Font Example") text(5, 5, "Bold text", font = 2) text(5, 3, "Italic text", font = 3) dev.off() ``` -------------------------------- ### svgstring: Create SVG String Source: https://context7.com/r-lib/svglite/llms.txt Returns SVG output as a string instead of writing to a file. This is useful for dynamic SVG generation in web applications like Shiny or for programmatic manipulation. ```APIDOC ## svgstring ### Description Returns SVG output as a string instead of writing to a file. Useful for dynamic SVG generation in web applications (e.g., Shiny) or for programmatic manipulation. ### Method `svgstring()` ### Parameters #### Path Parameters - **width** (numeric) - Width of the SVG in inches. Defaults to 7. - **height** (numeric) - Height of the SVG in inches. Defaults to 7. - **bg** (character) - Background color of the SVG. Defaults to "transparent". - **pointsize** (numeric) - Default point size in points. Defaults to 12. - **standalone** (logical) - If TRUE, includes the XML header. Defaults to TRUE. - **fix_text_size** (logical) - If TRUE, attempts to fix text width across renderers. Defaults to FALSE. - **scaling** (numeric) - A scaling factor for line widths and text sizes. Defaults to 1. - **id** (character) - An SVG ID to assign to the root `` element, useful for embedding. ### Request Example ```r library(svglite) # Basic usage - get SVG as string s <- svgstring(width = 8, height = 6) plot(rnorm(100), rnorm(100), main = "Scatter Plot", xlab = "X values", ylab = "Y values", pch = 19, col = rgb(0.2, 0.4, 0.8, 0.6)) dev.off() # Get the SVG content svg_content <- s() cat(substr(svg_content, 1, 500)) # Print first 500 characters # Progressive SVG building - check content during drawing s <- svgstring() s() # Empty SVG at start plot.new() s() # SVG with empty plot area text(0.5, 0.5, "Hello, SVG!") s() # SVG with text added dev.off() # Final complete SVG final_svg <- s() # Use in Shiny or web context # server <- function(input, output) { # output$plot <- renderUI({ # s <- svgstring(width = 10, height = 8) # plot(input$data) # dev.off() # HTML(s()) # }) # } ``` ### Response Returns the SVG content as a character string. Calling the returned function (e.g., `s()`) retrieves the current SVG output. ``` -------------------------------- ### Generate SVG String Directly with stringSVG Source: https://context7.com/r-lib/svglite/llms.txt Uses stringSVG to generate an SVG as a character string. This is a simpler alternative to svgstring() for one-off SVG creation. The output can be printed or saved to a file. Custom dimensions can be specified. ```r library(svglite) # Generate SVG string directly svg_string <- stringSVG( plot(1:10, main = "Quick Plot", col = "darkgreen", pch = 16) ) # Print the SVG cat(svg_string) # Save to file writeLines(svg_string, "quick_plot.svg") # Use with custom dimensions svg_large <- stringSVG( { par(mar = c(4, 4, 2, 1)) boxplot(mpg ~ cyl, data = mtcars, main = "MPG by Cylinders", col = c("lightblue", "lightgreen", "lightyellow")) }, width = 12, height = 8 ) ``` -------------------------------- ### Register Font Variant with svglite Source: https://context7.com/r-lib/svglite/llms.txt Registers a font variant with specific OpenType features. This is useful for enabling features like ligatures or stylistic sets. ```r library(svglite) # Register font variant with specific features register_variant( name = "Fira Code Ligatures", family = "Fira Code", features = font_feature(liga = TRUE, calt = TRUE) ) # Use variant in plot svglite("code_plot.svg") par(family = "Fira Code Ligatures") plot.new() text(0.5, 0.5, "=> -> != ==", cex = 2) # Shows ligatures if font supports them dev.off() ``` -------------------------------- ### Validate Malformed Alias Source: https://github.com/r-lib/svglite/blob/main/tests/testthat/_snaps/text-fonts.md Demonstrates how `validate_aliases` throws an error when an alias is provided as a character vector instead of a single string. ```R validate_aliases(list(mono = letters), list()) ``` -------------------------------- ### htmlSVG: View SVG in Browser Source: https://context7.com/r-lib/svglite/llms.txt Runs plotting code and displays the resulting SVG directly in the RStudio Viewer or a web browser. This is convenient for interactive development and testing. ```APIDOC ## htmlSVG ### Description Runs plotting code and displays the resulting SVG in the RStudio Viewer or web browser. Useful for interactive development and testing. ### Method `htmlSVG()` ### Parameters #### Path Parameters - **plot_code** (expression) - The R code that generates the plot. - **width** (numeric) - Width of the SVG in inches. Defaults to 7. - **height** (numeric) - Height of the SVG in inches. Defaults to 7. - **bg** (character) - Background color of the SVG. Defaults to "transparent". - **pointsize** (numeric) - Default point size in points. Defaults to 12. - **standalone** (logical) - If TRUE, includes the XML header. Defaults to TRUE. - **fix_text_size** (logical) - If TRUE, attempts to fix text width across renderers. Defaults to FALSE. - **scaling** (numeric) - A scaling factor for line widths and text sizes. Defaults to 1. - **id** (character) - An SVG ID to assign to the root `` element, useful for embedding. ### Request Example ```r library(svglite) # View plot directly in RStudio Viewer or browser if (interactive() && require("htmltools")) { # Simple plot htmlSVG(plot(1:10)) # Histogram with custom settings htmlSVG( hist(rnorm(100), col = "lightblue", main = "Random Data"), width = 8, height = 6, bg = "white" ) # ggplot2 integration library(ggplot2) htmlSVG( print(ggplot(mtcars, aes(wt, mpg)) + geom_point(aes(color = factor(cyl))) + theme_minimal()), width = 10, height = 7 ) } ``` ### Response Displays the generated SVG in an interactive viewer. Does not return a value. ``` -------------------------------- ### Open Plot in Default SVG Editor with editSVG Source: https://context7.com/r-lib/svglite/llms.txt Uses editSVG to run plotting code and open the resulting SVG in the system's default SVG viewer or editor. This is useful for immediate visual inspection and manual post-processing. Supports basic and complex visualizations with custom dimensions. ```r library(svglite) # Open plot in default SVG editor if (interactive()) { # Basic usage editSVG(plot(1:10)) # Complex visualization for editing editSVG( { par(mfrow = c(1, 2)) plot(cars, main = "Speed vs Distance") hist(cars$speed, main = "Speed Distribution", col = "coral") }, width = 14, height = 6 ) # Contour plot for vector editing editSVG( contour(volcano, main = "Volcano Topology"), width = 10, height = 8 ) } ``` -------------------------------- ### View SVG plots with htmlSVG Source: https://context7.com/r-lib/svglite/llms.txt Use htmlSVG to render plotting code and display the resulting SVG directly in the RStudio Viewer or a web browser. Requires the htmltools package. ```r library(svglite) # View plot directly in RStudio Viewer or browser if (interactive() && require("htmltools")) { # Simple plot htmlSVG(plot(1:10)) # Histogram with custom settings htmlSVG( hist(rnorm(100), col = "lightblue", main = "Random Data"), width = 8, height = 6, bg = "white" ) # ggplot2 integration library(ggplot2) htmlSVG( print(ggplot(mtcars, aes(wt, mpg)) + geom_point(aes(color = factor(cyl))) + theme_minimal()), width = 10, height = 7 ) } ``` -------------------------------- ### Programmatically manipulate SVG with xmlSVG Source: https://context7.com/r-lib/svglite/llms.txt Use xmlSVG to run plotting code and obtain the SVG output as an xml2 document object. This is useful for post-processing and programmatic inspection of SVG elements. ```r library(svglite) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.