2020-12-22為ggplot圖形標(biāo)記markdown文字

原文:https://cran.r-project.org/web/packages/ggtext/vignettes/plotting_text.html

ggtext包定義了兩個新的geoms, geom_richtext()和geom_textbox()翅睛,用于為圖形進(jìn)行文本標(biāo)記匿又, 分別繪制簡單的文本標(biāo)記(沒有自動換行)和文本框(帶自動換行)

使用geom_richtext()理肺,能將markdown形式的文本標(biāo)置于圖形中⊥龊牵可以看做是以前常用的geom_label()或geom_text()的代替品。

例子1——簡單文本標(biāo)記

  • 使用r2的值添加圖形注釋助琐,用iris數(shù)據(jù)為例憎账,用傳統(tǒng)的geom_text()標(biāo)記如下:
library(ggplot2)
library(dplyr)
library(glue)

iris_cor <- iris %>% 
  group_by(Species) %>%
  summarize(r_square = cor(Sepal.Length, Sepal.Width)^2) %>%
  mutate(
    # location of each text label in data coordinates
    Sepal.Length = 8, Sepal.Width = 4.5,
    # text label containing r^2 value 
    label = glue("r^2 = {round(r_square, 2)}")
  )

iris_cor
#> # A tibble: 3 x 5
#>   Species    r_square Sepal.Length Sepal.Width label     
#>   <fct>         <dbl>        <dbl>       <dbl> <glue>    
#> 1 setosa        0.551            8         4.5 r^2 = 0.55
#> 2 versicolor    0.277            8         4.5 r^2 = 0.28
#> 3 virginica     0.209            8         4.5 r^2 = 0.21

iris_facets <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
  geom_point() + 
  geom_smooth(method = "lm", formula = y ~ x) +
  facet_wrap(~Species) +
  theme_bw()

iris_facets + 
  geom_text(
    data = iris_cor,
    aes(label = label),
    hjust = 1, vjust = 1
image.png

代碼可以work趴捅,但是結(jié)果不讓人滿意垫毙。1)r是數(shù)學(xué)變量,應(yīng)該斜體拱绑。2)2應(yīng)該是上標(biāo)不是^2综芥。用geom_richtext()可以輕松創(chuàng)建markdown標(biāo)記。

library(ggtext)

iris_cor_md <- iris_cor %>% 
  mutate(
    # markdown version of text label
    label = glue("*r*<sup>2</sup> = {round(r_square, 2)}")
  )

iris_cor_md
#> # A tibble: 3 x 5
#>   Species    r_square Sepal.Length Sepal.Width label                 
#>   <fct>         <dbl>        <dbl>       <dbl> <glue>                
#> 1 setosa        0.551            8         4.5 *r*<sup>2</sup> = 0.55
#> 2 versicolor    0.277            8         4.5 *r*<sup>2</sup> = 0.28
#> 3 virginica     0.209            8         4.5 *r*<sup>2</sup> = 0.21

iris_facets + 
  geom_richtext(
    data = iris_cor_md,
    aes(label = label),
    hjust = 1, vjust = 1
  )
image.png

默認(rèn)情況下猎拨,geom_richtext() 要給文本加一個框膀藐,可以通過設(shè)置填充色和外框線的顏色讓它不可見 (fill = NA, label.colour = NA)屠阻。

iris_facets + 
  geom_richtext(
    data = iris_cor_md,
    aes(label = label),
    hjust = 1, vjust = 1,
    # remove label background and outline
    fill = NA, label.color = NA,
    # remove label padding, since we have removed the label outline
    label.padding = grid::unit(rep(0, 4), "pt") 
  )
image.png

如同ggplot2一樣,可以各自選擇偏愛的標(biāo)記線额各、填充和文章的顏色国觉。

iris_facets + 
  aes(colour = Species) +
  geom_richtext(
    data = iris_cor_md,
    aes(
      label = label,
      fill = after_scale(alpha(colour, .2))
    ),
    text.colour = "black",
    hjust = 1, vjust = 1
  ) +
  theme(legend.position = "none")
image.png

還可以旋轉(zhuǎn)文字標(biāo)記(雖然不建議這么做)。

iris_facets + 
  aes(colour = Species) +
  geom_richtext(
    data = iris_cor_md,
    aes(
      x = 7.5,
      label = label,
      fill = after_scale(alpha(colour, .2))
    ),
    text.colour = "black",
    hjust = 1, vjust = 1,
    angle = 30
  ) +
  theme(legend.position = "none")
image.png

文本框

用geom_textbox()為圖形添加markdown形式的文本框(帶自動換行)虾啦÷榫鳎可以指定文本框的寬度,可以是絕對寬度(如"cm","pt", "in")傲醉,也可以是相對寬度(如"npc")蝇闭。

df <- data.frame(
  x = 0.1,
  y = 0.8,
  label = "*Lorem ipsum dolor sit amet,* consectetur adipiscing
elit. Quisque tincidunt eget arcu in pulvinar. Morbi varius leo
vel consectetur luctus. **Morbi facilisis justo non fringilla.**
Vivamus sagittis sem felis, vel lobortis risus mattis eget. Nam
quis imperdiet felis, in convallis elit."
)

p <- ggplot() +
  geom_textbox(
    data = df,
    aes(x, y, label = label),
    width = grid::unit(0.73, "npc"), # 73% of plot panel width
    hjust = 0, vjust = 1
  ) +
  xlim(0, 1) + ylim(0, 1)

p
image.png

如果改變了圖形的寬度,文本框會隨著改變硬毕,文本自動適應(yīng)呻引。


image.png

用hjust和vjust對齊x和y軸定義的參考點(diǎn),它不會影響文本框中的文本吐咳。文本框的文本對齊逻悠,可以用halign和valign。例如用halign=0.5進(jìn)行中心文本對齊挪丢。

ggplot() +
  geom_textbox(
    data = df,
    aes(x, y, label = label),
    width = grid::unit(0.73, "npc"), # 73% of plot panel width
    hjust = 0, vjust = 1,
    halign = 0.5 # centered text
  ) +
  xlim(0, 1) + ylim(0, 1)
image.png

文本框雖然不能任意角度旋轉(zhuǎn)蹂风,但是可以有四個選擇。

df <- data.frame(
  x = 0.5,
  y = 0.5,
  label = "The quick brown fox jumps over the lazy dog.",
  orientation = c("upright", "left-rotated", "inverted", "right-rotated")
)

ggplot() +
  geom_textbox(
    data = df,
    aes(x, y, label = label, orientation = orientation),
    width = grid::unit(1.5, "in"),
    height = grid::unit(1.5, "in"),
    box.margin = grid::unit(rep(0.25, 4), "in"),
    hjust = 0, vjust = 1
  ) +
  xlim(0, 1) + ylim(0, 1) +
  scale_discrete_identity(aesthetics = "orientation")
image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末乾蓬,一起剝皮案震驚了整個濱河市惠啄,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌任内,老刑警劉巖撵渡,帶你破解...
    沈念sama閱讀 217,185評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異死嗦,居然都是意外死亡趋距,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,652評論 3 393
  • 文/潘曉璐 我一進(jìn)店門越除,熙熙樓的掌柜王于貴愁眉苦臉地迎上來节腐,“玉大人,你說我怎么就攤上這事摘盆∫砣福” “怎么了?”我有些...
    開封第一講書人閱讀 163,524評論 0 353
  • 文/不壞的土叔 我叫張陵孩擂,是天一觀的道長狼渊。 經(jīng)常有香客問我,道長类垦,這世上最難降的妖魔是什么狈邑? 我笑而不...
    開封第一講書人閱讀 58,339評論 1 293
  • 正文 為了忘掉前任城须,我火速辦了婚禮,結(jié)果婚禮上米苹,老公的妹妹穿的比我還像新娘糕伐。我一直安慰自己,他們只是感情好驱入,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,387評論 6 391
  • 文/花漫 我一把揭開白布赤炒。 她就那樣靜靜地躺著,像睡著了一般亏较。 火紅的嫁衣襯著肌膚如雪莺褒。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,287評論 1 301
  • 那天雪情,我揣著相機(jī)與錄音遵岩,去河邊找鬼。 笑死巡通,一個胖子當(dāng)著我的面吹牛尘执,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播宴凉,決...
    沈念sama閱讀 40,130評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼誊锭,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了弥锄?” 一聲冷哼從身側(cè)響起丧靡,我...
    開封第一講書人閱讀 38,985評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎籽暇,沒想到半個月后温治,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,420評論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡戒悠,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,617評論 3 334
  • 正文 我和宋清朗相戀三年熬荆,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片绸狐。...
    茶點(diǎn)故事閱讀 39,779評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡卤恳,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出寒矿,到底是詐尸還是另有隱情纬黎,我是刑警寧澤,帶...
    沈念sama閱讀 35,477評論 5 345
  • 正文 年R本政府宣布劫窒,位于F島的核電站,受9級特大地震影響拆座,放射性物質(zhì)發(fā)生泄漏主巍。R本人自食惡果不足惜冠息,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,088評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望孕索。 院中可真熱鬧逛艰,春花似錦、人聲如沸搞旭。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,716評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽肄渗。三九已至镇眷,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間翎嫡,已是汗流浹背欠动。 一陣腳步聲響...
    開封第一講書人閱讀 32,857評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留惑申,地道東北人具伍。 一個月前我還...
    沈念sama閱讀 47,876評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像圈驼,于是被迫代替她去往敵國和親人芽。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,700評論 2 354

推薦閱讀更多精彩內(nèi)容