Search code examples
rsvgggplot2sizescale

ggplot2 grid.export plot size SVG


How can I specify the width and height of the final SVG when I do:

print(plot)
saveXML(grid.export()$svg)

I'm producing plots for a web application in SVG. I was using ggplot2 and saving the plot using ggsave which allowed me to specify size in inches for width and height. I worked great. I now needed to perform annotations on the SVG and it seemed that ggsave did not work, so I'm forced to use the grid.export approach presented above. The only aspect I seem to have control is the resolution, which allows me to make plots smaller. However, while ggsave made all the text and point size scale to a bigger size, the grid.export approach changing the resolution can make the plot smaller, but just by makes everything smaller so the plot reads worse.

For instance, setting width and height to 3

ggsave version:

img

grid.export version:

img


Solution

  • What I managed to do is define a new base_size on the theme to compensate the resolution scaling:

    base.size = 10 * (7/size)
    resolution = 72 * (size/7)
    
    if (length(plot$theme) == 0) plot <- plot + theme_gdocs();
    
    plot$theme$text$size = base.size
    
    mysvg <- grid.export(res=resolution)