File: svg.R

package info (click to toggle)
r-cran-vdiffr 1.0.8-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 880 kB
  • sloc: cpp: 1,744; sh: 13; makefile: 5
file content (59 lines) | stat: -rw-r--r-- 1,431 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
make_testcase_file <- function(fig_name) {
  file <- tempfile(fig_name, fileext = ".svg")
  structure(file, class = "vdiffr_testcase")
}

#' Default SVG writer
#'
#' This is the default SVG writer for vdiffr test cases. It uses
#' embedded versions of [svglite](https://svglite.r-lib.org),
#' [harfbuzz](https://harfbuzz.github.io/), and the Liberation and
#' Symbola fonts in order to create deterministic SVGs.
#'
#' @param plot A plot object to convert to SVG. Can be a ggplot2 object,
#'   a [recorded plot][grDevices::recordPlot], or any object with a
#'   [print()][base::print] method.
#' @param file The file to write the SVG to.
#' @param title An optional title for the test case.
#'
#' @export
write_svg <- function(plot, file, title = "") {
  svglite(file)
  on.exit(grDevices::dev.off())
  print_plot(plot, title)
}

print_plot <- function(p, title = "") {
  UseMethod("print_plot")
}

#' @export
print_plot.default <- function(p, title = "") {
  print(p)
}

#' @export
print_plot.ggplot <- function(p, title = "") {
  if (title != "" && !"title" %in% names(p$labels)) {
    p <- p + ggplot2::ggtitle(title)
  }
  if (!length(p$theme)) {
    p <- p + ggplot2::theme_test()
  }
  print(p)
}

#' @export
print_plot.grob <- function(p, title) {
  grid::grid.draw(p)
}

#' @export
print_plot.recordedplot <- function(p, title) {
  grDevices::replayPlot(p)
}

#' @export
print_plot.function <- function(p, title) {
  p()
}