How to save a plot made with ggplot2 as 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()
79278 次浏览

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.

Another option is using the save_plot function from the sjPlot package. It is also possible to save the ggplot as the following file types: ".png", ".jpg", ".svg" or ".tif". Just replace the extension to whatever you want. Here is a reproducible example:

library(ggplot2)
library(sjPlot)
#> Install package "strengejacke" from GitHub (`devtools::install_github("strengejacke/strengejacke")`) to load all sj-packages at once!
p <- ggplot(diamonds,(aes(x = clarity, fill = cut))) +
geom_bar()
p

# save plot
save_plot("your_plot.svg", fig = p, width=10, height=8)
#> quartz_off_screen
#>                 2

Created on 2022-08-23 with reprex v2.0.2

The output of the saved plot:

enter image description here