ggtext包是ggplot2的一个扩展包,为ggplot2 提供了富文本(Markdown、 HTML、 CSS等)支持,用于ggplot2图片展示种注解(图标题,字幕,标题,轴标签,图例,颜色、格式、公式等)并可视化文本数据。

安装 ggtext


# 安装ggtext 
install.packages("ggtext")

下面用一个简单的示例展示:


library(ggplot2)
library(dplyr)
library(glue)
library(ggthemes)
library(ggtext)

# https://wilkelab.org/ggtext/articles/plotting_text.html
iris_cor <- iris %>%
    group_by(Species) %>%
    # 计算相关系数
    summarize(r = cor(Sepal.Length, Sepal.Width)) %>%
    mutate(
        # 定义相关系数r^2
        Sepal.Length = 8,
        Sepal.Width = 4.5,
        label = glue("r = {round(r, 2)}")
    )

iris_cor_md <- iris_cor %>%
    # markdown语法标签
    mutate(label = glue("*r* = {round(r, 2)}"))

ggplot(iris, aes(Sepal.Length, Sepal.Width, color = Species)) +
    geom_point() +
    geom_richtext(
        data = iris_cor_md,
        aes(label = label,
            fill = after_scale(alpha(colour, .2))),
        text.colour = "black",
        hjust = 1,
        vjust = 1
    ) +
    # HTML语法标签
    labs(
        title = "**Fisher's *Iris* dataset**
    <span style='font-size:11pt'>Sepal width vs. sepal length for three *Iris* species</span>",
    x = "Sepal length (cm)",
    y = "Sepal width (cm)"
    ) +
    geom_smooth(method = "lm", formula = y ~ x) +
    # 分面
    facet_wrap( ~ Species, labeller = label_both) +
    theme_few() +
    theme(plot.title = element_markdown(lineheight = 1.1),
          legend.position = "none")

参考资料:

1.https://wilkelab.org/ggtext/articles/plotting_text.html