如何保存使用ggplot2作为SVG的绘图

Mat*_*unz 54 svg r ggplot2

我要救一个堆叠面积图(与代码的关系的例子可以发现,这里与制造)GGPLOT2SVG.尝试使用开罗套餐,但结果很糟糕.

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()
Run Code Online (Sandbox Code Playgroud)

E10*_*00i 74

实际上非常简单,除了ggplot2之外不需要其他包.只需正确使用ggsave.一些示例代码:

    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)
Run Code Online (Sandbox Code Playgroud)

希望对你有效.

  • 今天尝试了这个,得到了错误:`## loadNamespace(name)中的错误:没有名为'svglite'的包.已安装且有效.不知道为什么这个没有安装在ggplot2上. (10认同)
  • 如果您收到该消息,请尝试使用`install.packages('svglite')` (7认同)
  • > ggsave(last_plot(),filename ="按年度达到的累积社区(单调).svg",宽度= 6.0,高度= 6.0/1.5)match_family_(字体,粗体,斜体)出错:Fontconfig错误:无法匹配字体图案 (2认同)
  • 你需要在 Linux 上使用 `libcairo2-dev` 来编译 `svglite` 需要的 `gdtools`。 (2认同)
  • 这个答案是误导的。ggplot2不是唯一需要的软件包。如评论所述,`svglite`也是必需的。 (2认同)