之所以出现中文乱码是因为R环境只载入了三种英文字体,没有中文字体可用
解决办法就是从系统字体中载入中文字体,showtext包(会依赖sysfonts包)
library(showtext)
font_add("SmileySans", regular = "../data/SmileySans-Oblique-2.ttf") # regular参数填font文件的path
showtext_auto(enable = TRUE) # 自动启用
温馨提示,font是有版权的…
# 测试
library(ggplot2)
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point() +
labs(x = "引擎大小(L)", y = "高速燃油量(mpg)") +
theme(text = element_text(family = "SmileySans"))
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point() +
xlab("排量") +
theme(axis.title.x = element_text(family = "SmileySans"))
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point() +
scale_y_continuous(breaks = seq(15, 40, by = 10), labels = c("十五","二十五","三十五")) +
theme(axis.text.y = element_text(family = "SmileySans"))
如上,可以从“全局”层面对text设置,也可以对“局部”某处的text进行单独设置
P.S.
library(showtext)
showtext_auto(enable = TRUE) # 自动启用
不指定具体font,(不出意外的话)也可以解决中文乱码;
经个人测试,showtext里面是自带有中英文字体的(不确定哈)
Warning in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y, :
font family 'SmileySans' not found, will use 'wqy-microhei' instead
showtext更重要作用可能在于解决 plot -> PDF 过程中的乱码问题
showtext makes it easy to use various types of fonts (TrueType,
OpenType, Type 1, web fonts, etc.) in R plots. The motivation to
develop this package is that using non-standard fonts in R plots
(especially for PDF device) is not straightforward, for example, when
creating PDF with Chinese characters. This is because most of the
standard fonts used by pdf() do not contain Chinese character glyphs,
and users could hardly use system fonts in R.
另外提一点,在rticles包的助力下,中文Rmd -> (Latex) -> PDF 也可以丝滑完成
最后
感谢Hadley,谢益辉等一众大佬的辛勤付出,让我拥有这些优秀的工具。感谢!