Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a plot made with ggplot2 as SVG

Tags:

r

ggplot2

svg

I want to save a stacked area plot (Plot example with code can be found here) made with ggplot2 as SVG. Tried it with the Cairo package but the outcome is bad.

library(ggplot2)
library(grid)
library(Cairo)
...

#png(output_file, width=800, height=400)
Cairo(800,400,file=paste(output_file, ".svg", sep=""),type="svg",bg="transparent",pointsize=8, units="px",dpi=400)

gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name=="panel"] <- "off"
grid.draw(gt)

dev.off()
like image 958
Matthias Munz Avatar asked Sep 01 '12 10:09

Matthias Munz


People also ask

How do I save a plot in ggplot2?

You can either print directly a ggplot into PNG/PDF files or use the convenient function ggsave() for saving a ggplot. The default of ggsave() is to export the last plot that you displayed, using the size of the current graphics device. It also guesses the type of graphics device from the extension.

Can R Save As SVG?

Second, in R you can save a plot as Scalable Vector Graphics (SVG) with the svg function.

How do you save a file as a SVG?

Click the File options menu in the top right corner and select Print or press Ctrl + P . Select Print to File and choose SVG as the Output format. Choose a name and folder in which to save the file, then click Print. The SVG file will be saved in the folder you chose.

How do I save ggplot as EPS?

The plot can be saved in the eps format using the ggplot. save() method, which takes as argument the string name of the plot.


1 Answers

Saving a plot made with ggplot2 as an SVG is straightforward using the ggsave function.

However, additional package(s) beyond ggplot2 may be required, such as svglite.

Some sample code:

    require("ggplot2")
#some sample data
    head(diamonds) 
#to see actually what will be plotted and compare 
    qplot(clarity, data=diamonds, fill=cut, geom="bar")
#save the plot in a variable image to be able to export to svg
    image=qplot(clarity, data=diamonds, fill=cut, geom="bar")
#This actually save the plot in a image
    ggsave(file="test.svg", plot=image, width=10, height=8)

Hope it works for you.

like image 81
E1000i Avatar answered Oct 16 '22 17:10

E1000i