R

近期使用R绘图遇到两个问题

1. 使用不同的字体

2. 保存 plot 至 pdf 当字体嵌入pdf (embed the font)


使用extrafont和Ghostscript能够解决这两个问题。

1. Ghostscript

安装: http://www.ghostscript.com/download/gsdnld.html


2. extrafont (R package)

下面命令都是在R中执行

- 安装

> install.packages("extrafont")
> library(extrafont)      
> #这一步定位系统字体。比方C:WindowsFonts*.ttf, 须要几分钟的时间
> font_import()
> loadfonts()

- 使用

> #查看可用的font family
> fonts()
> library(ggplot2)
> #使用字体Times New Roman绘图
> p <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
  xlab("Weight") + ylab("Miles per Gallon") +
  theme(text=element_text(family="Times New Roman"))
> #保存pdf
> ggsave("font_ggplot.pdf", plot=p)

- 将字体嵌入pdf

> #指定ghostscript的路径
> Sys.setenv(R_GSCMD = "C:/Program Files/gs/gs9.05/bin/gswin32c.exe")
> #嵌入字体
> embed_fonts("font_ggplot.pdf", outfile="font_ggplot_embed.pdf")

所得到的font_ggplot_embed.pdf就是所须要的pdf啦!

能够使用Adobe Reader -> File -> Properties -> Fonts 来查看字体是否已嵌入

(以上内容部分来自http://cran.r-project.org/web/packages/extrafont/README.html)


Bonus:直接使用Ghostscript命令行嵌入字体到pdf

(在cmd中执行,别忘了将ghostscript增加环境变量)

gswin32c -sFONTPATH=C:WindowsFonts -sDEVICE=pdfwrite -dEmbedAllFonts=true -o output.pdf input.pdf



版权声明:本文博客原创文章,博客,未经同意,不得转载。

原文地址:https://www.cnblogs.com/mengfanrong/p/4731684.html