【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包实现的。

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.

因为一般系统字体放在标准目录下,所以我们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


从使用上看,我更喜欢这个包~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,298评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,701评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,078评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,687评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,018评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,410评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,729评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,412评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,124评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,379评论 2 242
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,903评论 1 257
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,268评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,894评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,014评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,770评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,435评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,312评论 2 260

推荐阅读更多精彩内容