【r<-包|字體】showtext:在R圖里面更簡單地使用字體

如何修改畫圖使用的字體這篇文章中诸尽,我介紹了一種解決R圖里字體的方案——extrafont包蠢箩。今天意外看到另一個解決字體問題的包乌昔,再次推薦和介紹一番隙疚。

showtext幫助用戶在圖中更好地使用多種類型字體,包括TrueType磕道、OpenType等供屉。該包主要嘗試做以下兩件事情:

  • 讓R知道這些字體
  • 讓這些字體繪制文本

該包的動力在于在R圖中使用非標準字體不方便,比如中文字體溺蕉。

簡單實例

library(showtext)
## Loading Google fonts (http://www.google.com/fonts)
font_add_google("Gochi Hand", "gochi")
font_add_google("Schoolbell", "bell")
font_add_google("Covered By Your Grace", "grace")
font_add_google("Rock Salt", "rock")

## Automatically use showtext to render text for future devices
showtext_auto()

## Tell showtext the resolution of the device,
## only needed for bitmap graphics. Default is 96
## showtext_opts(dpi = 96)

set.seed(123)
x = rnorm(10)
y = 1 + x + rnorm(10, sd = 0.2)
y[1] = 5
mod = lm(y ~ x)

## Plotting functions as usual
## Open a graphics device if you want, e.g.
## png("demo.png", 700, 600, res = 96)

op = par(cex.lab = 2, cex.axis = 1.5, cex.main = 2)
plot(x, y, pch = 16, col = "steelblue",
     xlab = "X variable", ylab = "Y variable", family = "gochi")
grid()
title("Draw Plots Before You Fit A Regression", family = "bell")
text(-0.5, 4.5, "This is the outlier", cex = 2, col = "steelblue",
     family = "grace")
abline(coef(mod))
abline(1, 1, col = "red")
par(family = "rock")
text(1, 1, expression(paste("True model: ", y == x + 1)),
     cex = 1.5, col = "red", srt = 20)
text(0, 2, expression(paste("OLS: ", hat(y) == 0.79 * x + 1.49)),
     cex = 1.5, srt = 15)
legend("topright", legend = c("Truth", "OLS"), col = c("red", "black"), lty = 1)

par(op)
image

在這個例子中我們首先導入了一些在線谷歌字體伶丐,然后用showtext_auto()函數告訴R控制圖的文本字體輸出,接下來的所有部分就和平常我們畫圖一樣疯特。

This example should work on most graphics devices, including pdf(), png(), postscript(), and on-screen devices such as windows() on Windows and x11() on Linux.

用法

分為以下幾步:

  • 載入字體
  • 打開繪圖設備
  • 聲明你想要使用showtext畫文本圖
  • 畫圖
  • 關閉畫圖設備

If you want to use showtext globally, you can call the function showtext_auto() once, and then all the devices after that will automatically use showtext to render text, as the example in the beginning shows.

If you want to have finer control on which part of the code should use showtext, functions showtext_begin() and showtext_end() will help.

載入字體

載入字體是通過sysfonts包實現(xiàn)的哗魂。

The easy way to load font into showtext is by calling font.add(family, regular), where family is the name that you assign to that font (so that later you can call par(family = …) to use this font in plotting), and regular is the path to the font file. That is to say, only knowing the “font name” is not enough, since they are usually system dependent. On the contrary, font file is the entity that actually provides the character glyphs.

因為一般系統(tǒng)字體放在標準目錄下,所以我們can use font.paths() to check the current search path or add a new one, and use font.files() to list available font files in the search path.

font.paths()
#> 'fond.paths()' is now renamed to 'font_paths()'
#> The old version still works, but consider using the new function in future code
#> [1] "/Library/Fonts"           "/Users/wsx/Library/Fonts"

font.files()
#> 'font.files()' is now renamed to 'font_files()'
#> The old version still works, but consider using the new function in future code
#>   [1] "Al Nile.ttc"                     "Al Tarikh.ttc"                  
#>   [3] "AlBayan.ttc"                     "AmericanTypewriter.ttc"         
#>   [5] "Andale Mono.ttf"                 "Apple Chancery.ttf"             
#>   [7] "AppleGothic.ttf"                 "AppleMyungjo.ttf"               
#>   [9] "Arial Black.ttf"                 "Arial Bold Italic.ttf"          
#>  [11] "Arial Bold.ttf"                  "Arial Italic.ttf"               
#>  [13] "Arial Narrow Bold Italic.ttf"    "Arial Narrow Bold.ttf"          
#>  [15] "Arial Narrow Italic.ttf"         "Arial Narrow.ttf"               
#>  [17] "Arial Rounded Bold.ttf"          "Arial Unicode.ttf"              
#>  [19] "Arial.ttf"                       "Athelas.ttc"                    
#>  [21] "Ayuthaya.ttf"                    "Baghdad.ttc"                    
#>  [23] "Bangla MN.ttc"                   "Bangla Sangam MN.ttc"           
#>  [25] "Baskerville.ttc"                 "Beirut.ttc"                     
#>  [27] "BigCaslon.ttf"                   "Bodoni 72 OS.ttc"               
#>  [29] "Bodoni 72 Smallcaps Book.ttf"    "Bodoni 72.ttc"                  
#>  [31] "Bodoni Ornaments.ttf"            "Bradley Hand Bold.ttf"          
#>  [33] "Brush Script.ttf"                "Chalkboard.ttc"                 
#>  [35] "ChalkboardSE.ttc"                "Chalkduster.ttf"                
#>  [37] "Charter.ttc"                     "Cochin.ttc"                     
#>  [39] "Comic Sans MS Bold.ttf"          "Comic Sans MS.ttf"              
#>  [41] "Copperplate.ttc"                 "Corsiva.ttc"                    
#>  [43] "Courier New Bold Italic.ttf"     "Courier New Bold.ttf"           
#>  [45] "Courier New Italic.ttf"          "Courier New.ttf"                
#>  [47] "Damascus.ttc"                    "DecoTypeNaskh.ttc"              
#>  [49] "Devanagari Sangam MN.ttc"        "DevanagariMT.ttc"               
#>  [51] "Didot.ttc"                       "DIN Alternate Bold.ttf"         
#>  [53] "DIN Condensed Bold.ttf"          "Diwan Kufi.ttc"                 
#>  [55] "Diwan Thuluth.ttf"               "EuphemiaCAS.ttc"                
#>  [57] "Farah.ttc"                       "Farisi.ttf"                     
#>  [59] "Futura.ttc"                      "Georgia Bold Italic.ttf"        
#>  [61] "Georgia Bold.ttf"                "Georgia Italic.ttf"             
#>  [63] "Georgia.ttf"                     "GillSans.ttc"                   
#>  [65] "Gujarati Sangam MN.ttc"          "GujaratiMT.ttc"                 
#>  [67] "Gurmukhi MN.ttc"                 "Gurmukhi Sangam MN.ttc"         
#>  [69] "Gurmukhi.ttf"                    "Herculanum.ttf"                 
#>  [71] "Hoefler Text Ornaments.ttf"      "Hoefler Text.ttc"               
#>  [73] "Impact.ttf"                      "InaiMathi-MN.ttc"               
#>  [75] "Iowan Old Style.ttc"             "ITFDevanagari.ttc"              
#>  [77] "Kailasa.ttc"                     "Kannada MN.ttc"                 
#>  [79] "Kannada Sangam MN.ttc"           "Kefa.ttc"                       
#>  [81] "Khmer MN.ttc"                    "Khmer Sangam MN.ttf"            
#>  [83] "Kokonor.ttf"                     "Krungthep.ttf"                  
#>  [85] "KufiStandardGK.ttc"              "Lao MN.ttc"                     
#>  [87] "Lao Sangam MN.ttf"               "Luminari.ttf"                   
#>  [89] "Malayalam MN.ttc"                "Malayalam Sangam MN.ttc"        
#>  [91] "Marion.ttc"                      "Microsoft Sans Serif.ttf"       
#>  [93] "Mishafi Gold.ttf"                "Mishafi.ttf"                    
#>  [95] "Mshtakan.ttc"                    "Muna.ttc"                       
#>  [97] "Myanmar MN.ttc"                  "Myanmar Sangam MN.ttc"          
#>  [99] "Nadeem.ttc"                      "NewPeninimMT.ttc"               
#> [101] "NISC18030.ttf"                   "Oriya MN.ttc"                   
#> [103] "Oriya Sangam MN.ttc"             "Papyrus.ttc"                    
#> [105] "Phosphate.ttc"                   "PlantagenetCherokee.ttf"        
#> [107] "PTMono.ttc"                      "PTSans.ttc"                     
#> [109] "PTSerif.ttc"                     "PTSerifCaption.ttc"             
#> [111] "Raanana.ttc"                     "Rockwell.ttc"                   
#> [113] "Sana.ttc"                        "Sathu.ttf"                      
#> [115] "Savoye LET.ttc"                  "Seravek.ttc"                    
#> [117] "Shree714.ttc"                    "SignPainter.ttc"                
#> [119] "Silom.ttf"                       "Sinhala MN.ttc"                 
#> [121] "Sinhala Sangam MN.ttc"           "Skia.ttf"                       
#> [123] "SnellRoundhand.ttc"              "Songti.ttc"                     
#> [125] "STIXGeneral.otf"                 "STIXGeneralBol.otf"             
#> [127] "STIXGeneralBolIta.otf"           "STIXGeneralItalic.otf"          
#> [129] "STIXIntDBol.otf"                 "STIXIntDReg.otf"                
#> [131] "STIXIntSmBol.otf"                "STIXIntSmReg.otf"               
#> [133] "STIXIntUpBol.otf"                "STIXIntUpDBol.otf"              
#> [135] "STIXIntUpDReg.otf"               "STIXIntUpReg.otf"               
#> [137] "STIXIntUpSmBol.otf"              "STIXIntUpSmReg.otf"             
#> [139] "STIXNonUni.otf"                  "STIXNonUniBol.otf"              
#> [141] "STIXNonUniBolIta.otf"            "STIXNonUniIta.otf"              
#> [143] "STIXSizFiveSymReg.otf"           "STIXSizFourSymBol.otf"          
#> [145] "STIXSizFourSymReg.otf"           "STIXSizOneSymBol.otf"           
#> [147] "STIXSizOneSymReg.otf"            "STIXSizThreeSymBol.otf"         
#> [149] "STIXSizThreeSymReg.otf"          "STIXSizTwoSymBol.otf"           
#> [151] "STIXSizTwoSymReg.otf"            "STIXVar.otf"                    
#> [153] "STIXVarBol.otf"                  "SukhumvitSet.ttc"               
#> [155] "SuperClarendon.ttc"              "Tahoma Bold.ttf"                
#> [157] "Tahoma.ttf"                      "Tamil MN.ttc"                   
#> [159] "Tamil Sangam MN.ttc"             "Telugu MN.ttc"                  
#> [161] "Telugu Sangam MN.ttc"            "Times New Roman Bold Italic.ttf"
#> [163] "Times New Roman Bold.ttf"        "Times New Roman Italic.ttf"     
#> [165] "Times New Roman.ttf"             "Trattatello.ttf"                
#> [167] "Trebuchet MS Bold Italic.ttf"    "Trebuchet MS Bold.ttf"          
#> [169] "Trebuchet MS Italic.ttf"         "Trebuchet MS.ttf"               
#> [171] "Verdana Bold Italic.ttf"         "Verdana Bold.ttf"               
#> [173] "Verdana Italic.ttf"              "Verdana.ttf"                    
#> [175] "Waseem.ttc"                      "Webdings.ttf"                   
#> [177] "Wingdings 2.ttf"                 "Wingdings 3.ttf"                
#> [179] "Wingdings.ttf"                   "Zapfino.ttf"

At present font.add() supports TrueType fonts(.ttf/.ttc) and OpenType fonts(*.otf), and adding new font type is trivial as long as FreeType supports it.

Note that showtext includes an open source CJK font WenQuanYi Micro Hei. If you just want to show CJK text in your graph, you do not need to add any extra font at all.

注意漓雅,there are many free fonts available and accessible on the web, for instance the Google Fonts project (https://www.google.com/fonts). sysfonts provides an interface to automatically download and register those fonts through the function font_add_google(), as the example below shows.

library(showtext)
font_add_google("Lobster", "lobster")

showtext_auto()

plot(1, pch = 16, cex = 3)
text(1, 1.1, "A fancy dot", family = "lobster", col = "steelblue", cex = 3)
image

更多例子和用法查看說明文檔https://github.com/yixuan/showtext


從使用上看录别,我更喜歡這個包~

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市邻吞,隨后出現(xiàn)的幾起案子组题,更是在濱河造成了極大的恐慌,老刑警劉巖抱冷,帶你破解...
    沈念sama閱讀 222,378評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件崔列,死亡現(xiàn)場離奇詭異,居然都是意外死亡旺遮,警方通過查閱死者的電腦和手機赵讯,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,970評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來耿眉,“玉大人边翼,你說我怎么就攤上這事∶簦” “怎么了组底?”我有些...
    開封第一講書人閱讀 168,983評論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長西傀。 經常有香客問我,道長桶癣,這世上最難降的妖魔是什么拥褂? 我笑而不...
    開封第一講書人閱讀 59,938評論 1 299
  • 正文 為了忘掉前任,我火速辦了婚禮牙寞,結果婚禮上饺鹃,老公的妹妹穿的比我還像新娘莫秆。我一直安慰自己,他們只是感情好悔详,可當我...
    茶點故事閱讀 68,955評論 6 398
  • 文/花漫 我一把揭開白布镊屎。 她就那樣靜靜地躺著,像睡著了一般茄螃。 火紅的嫁衣襯著肌膚如雪缝驳。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,549評論 1 312
  • 那天归苍,我揣著相機與錄音用狱,去河邊找鬼。 笑死拼弃,一個胖子當著我的面吹牛夏伊,可吹牛的內容都是我干的。 我是一名探鬼主播吻氧,決...
    沈念sama閱讀 41,063評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼溺忧,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了盯孙?” 一聲冷哼從身側響起鲁森,我...
    開封第一講書人閱讀 39,991評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎镀梭,沒想到半個月后刀森,有當地人在樹林里發(fā)現(xiàn)了一具尸體,經...
    沈念sama閱讀 46,522評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡报账,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,604評論 3 342
  • 正文 我和宋清朗相戀三年研底,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片透罢。...
    茶點故事閱讀 40,742評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡榜晦,死狀恐怖,靈堂內的尸體忽然破棺而出羽圃,到底是詐尸還是另有隱情乾胶,我是刑警寧澤,帶...
    沈念sama閱讀 36,413評論 5 351
  • 正文 年R本政府宣布朽寞,位于F島的核電站识窿,受9級特大地震影響,放射性物質發(fā)生泄漏脑融。R本人自食惡果不足惜喻频,卻給世界環(huán)境...
    茶點故事閱讀 42,094評論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望肘迎。 院中可真熱鬧甥温,春花似錦锻煌、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,572評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至狰挡,卻和暖如春捂龄,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背圆兵。 一陣腳步聲響...
    開封第一講書人閱讀 33,671評論 1 274
  • 我被黑心中介騙來泰國打工跺讯, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人殉农。 一個月前我還...
    沈念sama閱讀 49,159評論 3 378
  • 正文 我出身青樓刀脏,卻偏偏與公主長得像,于是被迫代替她去往敵國和親超凳。 傳聞我的和親對象是個殘疾皇子愈污,可洞房花燭夜當晚...
    茶點故事閱讀 45,747評論 2 361

推薦閱讀更多精彩內容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,346評論 0 10
  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的閱讀 13,493評論 5 6
  • 我是實用主義者。耐心等待轮傍、一定會嫁給愛情之類的句子我不懂暂雹。我只知道,人生是關于體驗的创夜,如果連你自己都不去行動爭取杭跪,...
    氣微味甜閱讀 596評論 1 4
  • 我們在春風秋雨里無話不說涧尿,卻在春去秋來時失去了聯(lián)絡。蘇里檬贰,你在看嗎姑廉?陳思凌登陸了已有5年沒更新的知乎賬號,在舊貼里...
    六月醬閱讀 919評論 4 15
  • 1.理瓶機出口防護蓋板未遮蓋翁涤。生產部 2018年2月24日 2.hdpe灌裝機安全門未關閉桥言,且電眼損壞。生產部葵礼,設...
    桔子飛閱讀 451評論 0 0