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

R 如何将使用ggplot2制作的绘图保存为SVG,r,svg,ggplot2,R,Svg,Ggplot2,我想将使用ggplot2制作的堆叠面积图(可以找到带有代码的绘图示例)保存为SVG。尝试了开罗套餐,但结果很糟糕 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=

我想将使用ggplot2制作的堆叠面积图(可以找到带有代码的绘图示例)保存为SVG。尝试了开罗套餐,但结果很糟糕

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()
库(ggplot2)
图书馆(网格)
图书馆(开罗)
...
#png(输出_文件,宽度=800,高度=400)
Cairo(800400,文件=粘贴(输出文件“.svg”,sep=”“),type=“svg”,bg=“transparent”,pointsize=8,units=“px”,dpi=400)

gt使用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)

希望它对您有用。

有CRAN软件包,但您必须根据自己的系统从源代码构建。高分辨率png看起来确实不错,
ggsave
可用于此功能。
grGraphics
软件包中的
svg
设备是我的mac二进制文件的标准配置,无需调用
library
。看看它是否已安装。它工作正常。今天尝试了此操作,但出现错误:
##loadNamespace(名称)中出错:没有名为“svglite”的包。
。安装和工作。不确定为什么这不是随ggplot2安装的。如果您收到此消息,请尝试此
install.packages('svglite')
>ggsave(last_plot(),filename=“按年达到的累积社区(单调).svg”,width=6.0,height=6.0/1.5)match_family(字体、粗体、斜体)错误:Fontconfig错误:无法匹配字体模式您需要在linux上使用
libcairo2 dev
,才能编译
gdtools
,这是
svglite
所需的。这个答案有误导性<代码>ggplot2
不是唯一需要的软件包。作为注释状态,
svglite
也是必需的。