解决R语言绘图中的中文乱码问题
2018-08-22 本文已影响8人
混沌边缘的伊卡洛斯
网上一般的建议是在
plot
函数中使用family参数,这种方式虽然灵活,但是每次都要重复设置,显得麻烦,其实可以利用R的启动配置文件~/.Rprofile
来设置,然后使用中就不用重复输入了。
我的操作系统是macOS 10.13.6,R语言安装的是最新的3.5.1版本,从网上下载了免费的思源黑体(Source Han Sans)字体文件,下面以此为基础说一下操作步骤:
- 确定在
$HOME
目录中有.Rprofile
文件,如果你的系统中没有,可以用
touch ~/.Rprofile
的方法建立一个空白的配置文件。
- 用编辑器打开
.Rprofile
,输入如下配置信息:
# My profile file
# 选择绘图设备,macOS下一般默认也是quartz
if (.Platform$pkgType == "mac.binary"){
options(device="quartz")
}
# 设置Hook函数,在绘图设备启动的时候自动载入
setHook(packageEvent("grDevices", "onLoad"),
function(...) {
# 这里设置绘图窗口和字体的大小
grDevices::quartz.options(width = 7, height = 5, pointsize = 8)
# PDF输出
grDevices::pdf.options(family="Source Han Sans")
# 个人喜好,改变设备默认的serif和sans字体为中文字体
# 如果这里设置了,在下面familyset_hook函数中,
# 就可以使用par(family="sans")的方式来使用中文字体
# grDevices::quartzFonts(serif=grDevices::quartzFont(
# rep("Hiragino Mincho ProN W3", 4)))
# grDevices::quartzFonts(sans=grDevices::quartzFont(
# rep("Hiragino Maru Gothic ProN W4", 4)))
}
)
# 设置plot的Hook函数,在图形建立的时候自动载入
attach(NULL, name = "MacChineseEnv")
assign("familyset_hook",
function() {
if(names(dev.cur())=="quartz")
par(family="Source Han Sans")},
pos="MacChineseEnv")
setHook("plot.new", get("familyset_hook", pos="MacChineseEnv"))
# 加载经常需要使用的Library,例如ggplot2等
library("ggplot2")
# ggplot2使用中文字体的方式不一样,这里进行一次设定
theme_set(theme_get() + theme(text=element_text(family='Source Han Sans')))
message("##----- Successfully loaded .Rprofile -----##")
- 测试结果,启动R之后,输入
plot(-1:1, -1:1, type = "n", xlab = "Re", ylab = "Im")
K <- 16; text(exp(1i * 2 * pi * (1:K) / K), col = 2)
plot(1:10, 1:10, main = "text(...) examples\n~~~~~~~~~~~~~~",
sub = "R is GNU ©, but not ® ...")
mtext("显示中文也是没有问题的", side = 3)
points(c(6,2), c(2,1), pch = 3, cex = 4, col = "red")
text(6, 2, "the text is CENTERED around (x,y) = (6,2) by default",
cex = .8)
text(2, 1, "or Left/Bottom - JUSTIFIED at (2,1) by 'adj = c(0,0)'",
adj = c(0,0))
text(4, 9, expression(hat(beta) == (X^t * X)^{-1} * X^t * y))
text(4, 8.4, "expression(hat(beta) == (X^t * X)^{-1} * X^t * y)",
cex = .75)
text(4, 7, expression(bar(x) == sum(frac(x[i], n), i==1, n)))
结果如图
![](https://img.haomeiwen.com/i1749344/23db75e52356e077.png)
有兴趣的同学,可以试一下ggplot2的qplot函数,也是可以正常工作的😄