Search code examples
rggplot2svg

How to get SVG string from R ggplot image?


In R, suppose I have a ggplot object like p below from a tutorial:

library(ggplot2)
data <- data.frame(
        day = as.Date("2017-06-14") - 0:364,
        value = runif(365) + seq(-140, 224)^2 / 10000
)
p <- ggplot(data, aes(x=day, y=value)) +
        geom_line() +
        xlab("")

I don't want to see the image, and I don't want to save it to a file. What I would like is to get a string that is the SVG for this image without doing either of those things. Is that possible?


Solution

  • You can use svglite::svgstring():

    library(ggplot2)
    library(svglite)
    
    data <- data.frame(
      day = as.Date("2017-06-14") - 0:364,
      value = runif(365) + seq(-140, 224)^2 / 10000
    )
    
    s <- svgstring()
    
    ggplot(data, aes(x=day, y=value)) +
      geom_line() +
      xlab("")
    
    my_svg <- s()
    dev.off()
    

    Where my_svg is a string containing:

    <?xml version='1.0' encoding='UTF-8' ?>
    <svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' class='svglite' width='720.00pt' height='576.00pt' viewBox='0 0 720.00 576.00'>
    <defs>
      <style type='text/css'><![CDATA[
        .svglite line, .svglite polyline, .svglite polygon, .svglite path, .svglite rect, .svglite circle {
          fill: none;
          stroke: #000000;
          stroke-linecap: round;
          stroke-linejoin: round;
          stroke-miterlimit: 10.00;
        }
        .svglite text {
          white-space: pre;
        }
      ]]></style>
    ...