svglite R Package

repository·main·Indexed 41 days ago

https://github.com/r-lib/svglite

An R graphics device that produces clean, small, and highly editable SVG output. Optimized for speed and web use, svglite offers better text preservation and font support than the standard R svg() device by encoding text as styled <text> elements and supporting compressed .svgz output.

Tokens
621
Snippets
4
Records
5
Agent score
3%

What's inside svglite

  1. Font support and web font embedding in svglite

    main

    svglite uses the systemfonts package for font discovery, allowing access to all installed system fonts, including those registered via register_font(), register_variant(), add_fonts(), or require_font(). It correctly encodes non-standard weights and OpenType features (like ligatures) in the style block.

    To ensure SVGs look consistent on systems without the specific fonts installed, you can embed webfont @imports. You can use systemfonts::fonts_as_import() to automatically generate these imports, which can optionally embed the font data directly into the file.

  2. Use svglite for high-performance SVG rendering

    main

    The svglite() function provides a graphics device that is faster and produces smaller file sizes than the standard R svg() device. It is particularly useful for dynamically serving SVGs over the web. Unlike svg(), which converts glyphs to polygons, svglite() encodes text as styled <text> elements, preserving editability in vector drawing programs like Inkscape or Illustrator.

    library(svglite)
    
    x <- runif(1e3)
    y <- runif(1e3)
    tmp1 <- tempfile()
    
    svglite(tmp1)
    plot(x, y)
    dev.off()
  3. Install svglite

    main

    You can install the stable version of svglite from CRAN using install.packages(). To install the development version directly from GitHub, use the pak package.

    # Stable version from CRAN
    install.packages("svglite")
    
    # Development version from GitHub
    # install.packages("pak")
    pak::pak("r-lib/svglite")
  4. Build svglite from source

    main

    Building svglite from source requires the libpng system dependency. You must ensure your R configuration (e.g., ~/.R/Makevars) points to the include and lib folders of libpng.

    macOS (arm64) Example:

    1. Install libpng via Homebrew:
      brew install libpng
    2. Configure ~/.R/Makevars:
      CPPFLAGS += -I/opt/homebrew/include
      LDFLAGS += -L/opt/homebrew/lib
    brew install libpng
  5. Generate compressed .svgz output with svglite

    main

    To produce compressed (gzipped) SVG files, provide a file path with a .svgz or .svg.gz extension to the svglite() function. This significantly reduces file size for web delivery.

    tmp3 <- tempfile(fileext = ".svgz")
    svglite(tmp3)
    plot(x, y)
    invisible(dev.off())