前言
R语言默认可以自由使用的字体只有sans(系统默认), serif和 mono三种,如果想要自由使用自定义中文字体或者英文字体,比如手写字体、pop字体,甚至基本的宋体都有问题?那就需要借助第三方工具包,否则中文会乱码。本文主要介绍{showtext}和{extrafont}。
1.1 showtext离线,强烈推荐
优点:在Rmarkdown网页生成的图片中直接显示字体,生成在线图片时适用 缺点:不能用ggsave保存生成pdf文件,bug多,安装复杂
#options(tidyverse.quiet = TRUE)
#加载包不要masks等信息
library(tidyverse)
library(sysfonts)
#--------- 1 showtext离线文字用
library(showtext)
showtext_auto() # 自动使用字体,很重要!
font_families() # 查看可供使用的字体
#"sans" "serif" "mono" "wqy-microhei"
# 增加字体所在路径
font_paths() # 默认一般为C:/Windows/Fonts
font_add("simsunbold",regular = "SimSunBold.ttf")
font_add("simsun",regular = "simsun.ttc")
font_add("times",regular = "times.ttf")
font_add("timesbold",regular = "timesbd.ttf")
font_add("arial",regular = "arial.ttf")
font_add("arialbold",regular = "arialbd.ttf")
font_families() # 查看可供使用的字体,可见R系统加载了宋体 arial time粗体和常规
# [1] "sans" "serif" "mono" "source-han-serif-cn" "wqy-microhei"
# [6] "times" "SimSunBold" "simsunbold" "simsun" "timesbold" # [11] "arial" "arialbold"
#粗体宋体需要从网上下载ttf, https://www.fontke.com/font/23023735/download/)
#-------案例1 ggplot2+ 中宋体+英文times,
library(ggplot2)
showtext_opts(dpi = 300) #默认96
p <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
ggtitle("Fuel Efficiency of 32 Cars",
subtitle = "32种汽车的燃油效率") +
xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
theme(text=element_text(size=12,face="plain", family="timesbold"),
plot.title = element_text(size =12,family="timesbold"),
plot.subtitle = element_text(size =12,family="simsunbold"))
p
#R的Plots区有时字体不能随着size大小即时更新显示
#6英寸 X 6英寸 300 ppi图像的高度和宽度(以像素为单位)
ggsave("fonttest-win1.tiff", width = 6, height = 6)
ggsave("fonttest-win1.png", width = 6, height = 6)
ggsave("fonttest-win1.bmp", width = 6, height = 6)
#PDF
ggsave('fonttest-win1.pdf', width = 6, height = 6)
#cairo PDF
# dev.new()
# pacman::p_load(Cairo)
# #此时,family不再奏效cairo
# ggsave("fonttest-win2.pdf", p, width = 8, height =6 , device = cairo_pdf, family = "arial")
# dev.off()
#-------案例2 plot绘图+中宋体英文times
showtext_opts(dpi = 300)
set.seed(123)
x = rnorm(10)
y = 1 + x + rnorm(10, sd = 0.2)
y[1] = 5
mod = lm(y ~ x)
op = par(cex.lab = 1, cex.axis = 1, cex.main = 1)
plot(x, y, pch = 16, col = "steelblue",
xlab = "X variable", ylab = "Y variable", family = "times")
grid()
title("Draw Plots Before You Fit A Regression", family = "times")
text(-0.5, 4.5, "这是异常值", cex = 1, col = "steelblue",
family = "simsun")
abline(coef(mod))
abline(1, 1, col = "red")
par(family = "times")
text(1, 1, expression(paste("True model: ", y == x + 1)),
cex = 1, col = "red", srt = 20)
text(0, 2, expression(paste("OLS: ", hat(y) == 0.79 * x + 1.49)),
cex = 1, srt = 15)
legend("topright", legend = c("Truth", "OLS"), col = c("red", "black"), lty = 1)
par(op)
首次安装C:\Users\niezh\AppData\Local\R\win-library\4.2\extrafontdb\metrics,耗时15分钟。fonts() 列出字体命令可见,一些中文字体被编译成拼音。尽管plot界面显示正常,但是出发ggsave另存为PDF。
小结
“Showtext,核心函数font_add,可任意中文英文排版,强烈推荐。
”
本公众号建立了学术交流群(群),仅供SCI学术交流,人数有限需要实名制。入群请加笔者微信 popnie,请备注说明:姓名-学校(单位)-专业。