如何将用ggplot2创建的图表保存为SVG

87

我想将使用ggplot2创建的堆积面积图(包含代码的示例图可以在此处找到)保存为SVG格式。尝试使用Cairo包,但结果不佳。

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()

1
有一个名为RSvgDevice的CRAN软件包,但是根据您的系统,您必须从源代码构建。 - Andrie
高分辨率的PNG图像实际上看起来非常好,可以使用ggsave来保存。 - Paul Hiemstra
2
grGraphics 包中的 svg 设备已经与我的 Mac 二进制文件一起提供,无需调用 library。请检查它是否已安装。它可以正常工作。 - jverzani
2个回答

121

使用ggsave函数将使用ggplot2制作的图形保存为SVG格式非常简单。

但是,除了ggplot2之外,可能还需要其他软件包,例如svglite。

一些示例代码:

    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)
希望对你有用。

15
今天尝试了这个,出现了错误:## Error in loadNamespace(name): there is no package called 'svglite'。安装了它,现在可以正常使用了。不确定为什么它没有随 ggplot2 一起安装。 - Nikos Alexandris
11
如果您收到此消息,请尝试执行以下命令:install.packages('svglite') - alberto
2
ggsave(last_plot(), filename = "Cumulative Communities Reached by year (monotone).svg", width=6.0, height=6.0/1.5) 在 match_family_(font, bold, italic) 中出现错误: Fontconfig 错误:无法匹配字体模式。 - jzadra
3
在Linux上编译svglite所需的gdtools需要安装libcairo2-dev - Midnighter
6
这个回答有误导性。 ggplot2不是唯一需要的软件包。正如评论中所述,还需要安装svglite - luchonacho
显示剩余4条评论

1
另一种选择是使用来自 sjPlot 包的 save_plot 函数。还可以将 ggplot 保存为以下文件类型之一:".png"、".jpg"、".svg" 或 ".tif"。只需将扩展名替换为您想要的即可。这里是一个可重现的示例:
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

本文创建于2022-08-23,使用reprex v2.0.2

保存绘图的输出结果如下:

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接