R Plotting - Chinese Support
Different system font directories:
-
On Linux, fonts are typically located in /usr/share/fonts. You can use the fc-list
command to view them:
# fc-list
/usr/share/fonts/truetype/dejavu/DejaVuSerif-Bold.ttf: DejaVu Serif:style=Bold
/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf: DejaVu Sans Mono:style=Book
/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf: DejaVu Sans:style=Book
/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf: DejaVu Sans:style=Bold
/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf: DejaVu Sans Mono:style=Bold
/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf: DejaVu Serif:style=Book
-
On Windows, fonts are in the C:\Windows\Fonts directory, which you can open directly to view.
-
On macOS, fonts are located in /System/Library/Fonts and /Library/Fonts.
To view the system-supported font library, you can install showtext:
> install.packages("showtext", repos = "https://mirrors.ustc.edu.cn/CRAN/") # Install showtext
...
> font_files() # View fonts
path file family face version
1 /Library/Fonts Arial Unicode.ttf Arial Unicode MS Regular Version 1.01x
ps_name
1 ArialUnicodeMS
Seeing ArialUnicodeMS, we can use it:
pie3D(info, labels = names, explode = 0.1, main = "3D Pie Chart", family = "ArialUnicodeMS")
Loading Custom Fonts
Sometimes the system font library is not well supported. The showtext() function can load custom fonts. You can download a TTF font package and use the font_add() function to add it.
Here, we use Source Han Sans, a free font developed by Adobe and Google.
Official website: https://source.typekit.com/source-han-serif/cn/
GitHub address: https://github.com/adobe-fonts/source-han-sans/tree/release/OTF/SimplifiedChinese
After opening the link, choose one:
You can also download from a cloud drive: https://pan.baidu.com/s/14cRhgYvvYotVIFkRVd71fQ.
Download an OTF font, such as SourceHanSansSC-Bold.otf, and place the file in the directory where your code is executed:
Using the font library for a bar chart:
Example
# Load showtext
library(showtext);
# The first parameter sets the font name, the second parameter is the font path, in the same directory, we just write the font name
font_add("SyHei", "SourceHanSansSC-Bold.otf");
# Set file name, output as png
png(file = "tutorialpro-bar-cn.png")
cvd19 = c(83534,2640626,585493)
# Load font
showtext_begin();
barplot(cvd19,
main="COVID-19 Bar Chart",
barplot(
col=c("#ED1C24","#22B14C","#FFC90E"),
names.arg=c("China","USA","India"),
family='SyHei' # Set font library
)
# Remove font
showtext_end();