Last active
June 17, 2019 06:32
-
-
Save badbye/e95499736db2d892bf2ed9228a695f2c to your computer and use it in GitHub Desktop.
为不同系统设置不同的字体,保证R语言画出的图可以正常显示中文
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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('我也好') |
Author
badbye
commented
Nov 20, 2018
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment