72

我想保存使用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()
4

1 回答 1

106

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

希望对你有效。

于 2012-09-25T16:07:32.117 回答