不同系統(tǒng)的字體庫(kù)目錄:
Linux 一般在 /usr/share/fonts 下,我們可以使用 fc-list 命令查看:
# 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
Windows 字體在 C:\Windows\Fonts\ 文件下,直接打開就能看到了。
mac OS 字體在 /System/Library/Fonts 和 /Library/Fonts 目錄下。
系統(tǒng)支持的字體庫(kù),可以通過安裝 showtext 來查看:
> install.packages("showtext", repos = "https://mirrors.ustc.edu.cn/CRAN/") # 安裝 showtext ... > font_files() # 查看字體 path file family face version 1 /Library/Fonts Arial Unicode.ttf Arial Unicode MS Regular Version 1.01x ps_name 1 ArialUnicodeMS
看到有 ArialUnicodeMS,我們就可以用了:
pie3D(info,labels = names,explode = 0.1, main = "3D 圖",family = "ArialUnicodeMS")
系統(tǒng)的字體庫(kù)有時(shí)候不是支持的很好, showtext() 函數(shù)可以載入我們自定義的字體,可以下載字體包 ttf,然后使用 font_add() 函數(shù)添加。
這里我們使用思源黑體,思源黑體是 Adobe 與 Google 推出的一款開源字體。
官網(wǎng):https://source.typekit.com/source-han-serif/cn/
GitHub 地址:https://github.com/adobe-fonts/source-han-sans/tree/release/OTF/SimplifiedChinese
打開鏈接后,在里面選一個(gè)就好了:
可以下載個(gè) OTF 字體,比如 SourceHanSansSC-Bold.otf,將該文件文件放在當(dāng)前執(zhí)行的代碼文件中:
柱形圖使用字體庫(kù):
# 載入 showtext library(showtext); # 第一個(gè)參數(shù)設(shè)置字體名稱,第二個(gè)參數(shù)為字體庫(kù)路徑,同目錄下,我們寫字體庫(kù)名就可以了 font_add("SyHei", "SourceHanSansSC-Bold.otf"); # 設(shè)置文件名,輸出為 png png(file = "nhooo-bar-cn.png") cvd19 = c(83534,2640626,585493) #加載字體 showtext_begin(); barplot(cvd19, main="新冠疫情條形圖", col=c("#ED1C24","#22B14C","#FFC90E"), names.arg=c("中國(guó)","美國(guó)","印度"), family='SyHei' # 設(shè)置字體庫(kù) ) # 去掉字體 showtext_end();
3D 餅圖使用中文:
library(plotrix) library(showtext); # 第一個(gè)參數(shù)設(shè)置字體名稱,第二個(gè)參數(shù)為字體庫(kù)路徑,同目錄下,我們寫字體庫(kù)名就可以了 font_add("SyHei", "SourceHanSansSC-Bold.otf"); # 數(shù)據(jù)準(zhǔn)備 info = c(1, 2, 4, 8) # 命名 names = c("Google", "Nhooo", "Taobao", "Weibo") # 涂色(可選) cols = c("#ED1C24","#22B14C","#FFC90E","#3f48CC") # 設(shè)置文件名,輸出為 png png(file = "3d_pie_chart.png") #加載字體 showtext_begin(); # 繪制 3D 圖 pie3D(info,labels = names,explode = 0.1, main = "3D圖",family = "SyHei") # 去掉字體 showtext_end(); # 關(guān)閉圖形設(shè)備 dev.off();