【问题标题】:How to save a plot made with ggplot2 as SVG如何将使用 ggplot2 制作的绘图保存为 SVG
【发布时间】:2012-09-01 10:08:39
【问题描述】:

我想保存一个用 ggplot2 作为 SVG 制作的堆积面积图(可以找到带有代码的绘图示例here)。尝试使用 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()

【问题讨论】:

  • 有 CRAN 包 RSvgDevice,但你取决于你的系统,你必须从源代码构建。
  • 高分辨率的png其实很好看,可以用ggsave
  • grGraphics 包中的svg 设备是我的mac 二进制文件的标准配置,不需要library 调用。看看有没有安装。它工作正常。

标签: r svg ggplot2


【解决方案1】:

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

希望它对你有用。

【讨论】:

  • 今天试过了,得到了错误:## Error in loadNamespace(name): there is no package called 'svglite'。已安装并且可以正常工作。不知道为什么它没有沿着 ggplot2 安装。
  • 如果您收到该消息,请尝试此install.packages('svglite')
  • > ggsave(last_plot(), filename = "Cumulative Communities Reached by year (monotone).svg", width=6.0, height=6.0/1.5) match_family_中的错误(字体,粗体,斜体) : Fontconfig 错误:无法匹配字体模式
  • 您需要在 linux 上使用 libcairo2-dev 才能编译 gdtools 所需的 svglite
  • 这个答案具有误导性。 ggplot2 不是唯一需要的包。正如 cmets 所述,svglite 也是必需的。
猜你喜欢
  • 2013-07-07
  • 2022-10-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-25
  • 2014-08-22
  • 1970-01-01
  • 2016-03-20
  • 1970-01-01
相关资源
最近更新 更多