前言
之前,一个群里的群友,想要在它画的图上加入中文,保存为PDF之后,中文字符也不变成乱码。当时随手推荐了一个R package:showtext。回过头来,做一下整理😑
R Packages:showtext
这个工具的作者现在已经是教授了。在看R语言相关书籍的时候,经常会在译者名录中看见这个包de作者。大佬实锤了…
showtext 渲染中文的思路大概是:将文本转换为有颜色填充的多边形轮廓,以丢失一些实际的文本信息的代价,渲染文本(就是字成了图,不是原来的字了)
安装
install.packages("showtext")
简单示例
library(showtext)
## Loading Google fonts (https://fonts.google.com/)
font_add_google("Gochi Hand", "gochi")
font_add_google("Schoolbell", "bell")
## Automatically use showtext to render text
showtext_auto()
set.seed(123)
hist(rnorm(1000), breaks = 30, col = "steelblue", border = "white",
main = "", xlab = "", ylab = "")
title("Histogram of Normal Random Numbers", family = "bell", cex.main = 2)
title(ylab = "Frequency", family = "gochi", cex.lab = 2)
text(2, 70, "N = 1000", family = "bell", cex = 2.5)
首先在线加载可用的谷歌字体,然后使用showtext_auto()
函数,告诉R,我要用showtext渲染文本(globally),其他的和平时画图没啥差别。上面的示例适用于大多数图形设备,包括pdf、png、postscript、windows上的windows和Linux上的x11等。如果,只是想针对某一句话使用某字体,可以这样使用:
showtext_begin()
text(2, 70, "N = 1000", family = "bell", cex = 2.5)
showtext_end()
如此,就会只修改 N=1000的字体
加载字体
showtext 内置了sysfonts(一个package),可以自定义加载字体,使用方式如下,family
指定名称,以便后续调用,regular
是字体文件的位置:
font_add(family = "<family_name>", regular = "/path/to/font/file")
通常哈,字体文件存放在系统内相对固定的位置,比如Windows的一般在C:\Windows\Fonts
,可以使用font_paths
检查当前路径或添加新路径,并使用font_files
列出搜索路径中可用的字体文件😑
一个加载Windows系统字体文件的例子:
library(showtext)
## HeiTi font 中文字体 黑体
font_add("heiti", "simhei.ttf")
## Constantia font 包含斜体
font_add("constan", regular = "constan.ttf", italic = "constani.ttf")
# 告诉R,要用showtext了
showtext_auto()
library(ggplot2)
p <- ggplot(NULL, aes(x = 1, y = 1)) + ylim(0.8, 1.2) +
theme(axis.title = element_blank(), axis.ticks = element_blank(),
axis.text = element_blank()) +
annotate("text", 1, 1.1, family = "heiti", size = 15,
label = "\u4F60\u597D\uFF0C\u4E16\u754C") +
annotate("text", 1, 0.9, label = 'Chinese for "Hello, world!"',
family = "constan", fontface = "italic", size = 12)
## On-screen device
x11()
print(p)
## PNG
ggsave("load_fonts.png", width = 7, height = 4, dpi = 96)
## 不用之后,关掉
showtext_auto(FALSE)
有些系统上可能没有simhei.ttf之类的字体文件,其他的格式也没问题,比如 .ttc .otf格式。
网上也有很多免费字体,例如谷歌字体项目。sysfonts
提供了一个界面,可以通过font_add_google
自动下载这些字体。showtext 内置了一个开源的项目:文泉驿,囊括中文、日文、韩文。可以直接指定family = wqy-microhei
使用。或者可以使用Source Han Sans/Serif:
library(showtext)
font_install(source_han_serif())
font_families()
[1] "sans" "serif" "mono" "wqy-microhei"
[5] "source-han-serif-cn"
PS:用的时候,尽量就直接用showtext_auto()
,避免出现其他问题
更多详见
https://cran.rstudio.com/web/packages/showtext/vignettes/introduction.html
https://journal.r-project.org/archive/2015-1/qiu.pdf