0

I am working with a function that outputs an svg object. As I see the SVG object is essentially a string of characters. I was wondering how to 1) plot the svg output from the function 2) save this svg object to disk under an svg extension? I tried ggsave but just resulted in an error.

I am fairly new to svg handling, so would appreciate any inputs. Thanks!

FlyingPickle
  • 1,047
  • 1
  • 9
  • 19
  • 2
    This package could be of help https://cran.r-project.org/web/packages/svglite/svglite.pdf – sm925 Jan 10 '20 at 20:05
  • What error did you get exactly? It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions. – MrFlick Jan 10 '20 at 20:09

1 Answers1

2

1) I tried that for a package I was developing and it was not straightforward. In the end, I needed two libraries: rsvg and grImport2. Here is the code I used:

  tfile <- tempfile(fileext = ".svg")
  tfile2 <- tempfile(fileext = ".png")
  cat(svg_code, file=tfile)
  if (requireNamespace("rsvg", quietly = TRUE) && requireNamespace("grImport2", quietly = TRUE)) {
    rsvg::rsvg_svg(svg = tfile, tfile2)
    p <- grImport2::readPicture(tfile2)
    grImport2::grid.picture(p)
  } else {
    if (systemShow == FALSE && outFile == ''){
      warning("The figure cannot be rendered in the plot window. Please, use the arguments outFile and/or systemShow.")
    }
  }
  if (systemShow){
    utils::browseURL(tfile)
  }

The first conditional is in case the system does not allow the installation of either package. As you can see, you first need to write the svg code (svg_code) to a file, in this case temporary (tfile). Then, rsvg_svg writes a temporary png file (tfile2). Finally, grImport2::readPicture and grImport2::grid.picture show the converted file in the plot window. I also left the part where the user can set a boolean variable (systemShow) and the package will attempt to open the file on the default system svg viewer.

2) That one is much easier. You just need to write the code to a file as text, like cat(svg_code, file='path_to_file.svg').

vqf
  • 2,600
  • 10
  • 16