好色之徒

2020-12-22为ggplot图形标记markdown文字

2020-12-22  本文已影响0人  iColors

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

ggtext包定义了两个新的geoms, geom_richtext()和geom_textbox(),用于为图形进行文本标记, 分别绘制简单的文本标记(没有自动换行)和文本框(带自动换行)

使用geom_richtext(),能将markdown形式的文本标置于图形中。可以看做是以前常用的geom_label()或geom_text()的代替品。

例子1——简单文本标记

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,但是结果不让人满意。1)r是数学变量,应该斜体。2)2应该是上标不是^2。用geom_richtext()可以轻松创建markdown标记。

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

默认情况下,geom_richtext() 要给文本加一个框,可以通过设置填充色和外框线的颜色让它不可见 (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一样,可以各自选择偏爱的标记线、填充和文章的颜色。

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

还可以旋转文字标记(虽然不建议这么做)。

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

如果改变了图形的宽度,文本框会随着改变,文本自动适应。


image.png

用hjust和vjust对齐x和y轴定义的参考点,它不会影响文本框中的文本。文本框的文本对齐,可以用halign和valign。例如用halign=0.5进行中心文本对齐。

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

文本框虽然不能任意角度旋转,但是可以有四个选择。

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
上一篇下一篇

猜你喜欢

热点阅读