Skip to content

Instantly share code, notes, and snippets.

@badbye
Last active June 17, 2019 06:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save badbye/e95499736db2d892bf2ed9228a695f2c to your computer and use it in GitHub Desktop.
Save badbye/e95499736db2d892bf2ed9228a695f2c to your computer and use it in GitHub Desktop.
为不同系统设置不同的字体,保证R语言画出的图可以正常显示中文
Sys.setlocale("LC_CTYPE", "UTF-8")
.setDefaultFont = function(windowsFont = 'song', linuxFont = 'monaco', macOSFont = 'STHeiti'){
# set base font for different system
osType = as.character(Sys.info()["sysname"])
baseFont = ifelse(osType == 'Darwin', macOSFont,
ifelse(osType == 'Linux', linuxFont, windowsFont))
message(sprintf('System: %s; base font: %s', osType, baseFont))
# for base plot
par(family=baseFont)
# for ggplot2
ggplot2::theme_set(ggplot2::theme_gray(base_family = baseFont))
# if you are using knitr, set base font before each chunk
knitr::knit_hooks$set(base.font = function(before, options, envir){
if (before){
par(family='baseFont')
ggplot2::theme_set(ggplot2::theme_gray(base_family = baseFont))
}
})
knitr::opts_chunk$set(base.font=TRUE)
}
.setDefaultFont()
# test
# plot(1:10, main='你好')
# library(ggplot2)
# ggplot(iris) + geom_point(aes(Sepal.Length, Sepal.Width)) + ggtitle('我也好')
@badbye
Copy link
Author

badbye commented Nov 20, 2018

# 用法
source('https://gist.githubusercontent.com/badbye/e95499736db2d892bf2ed9228a695f2c/raw/16285b7a7c6f53a449c1965e57301be4d247b012/baseFont.R')

# 测试
plot(1:10, main='你好')
library(ggplot2)
ggplot(iris) + geom_point(aes(Sepal.Length, Sepal.Width)) + ggtitle('我也好')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment