如何在 ggplot 的 geom_text_repel 或 geom_text 标签中包含删除线文本?

How do I include strikethrough text in geom_text_repel or geom_text labels for ggplot?

是否可以向某些 geom_text/geom_text_repel 标签添加 删除线

问题提到您可以 斜体 使用以下标签:

library("ggplot2")
library("ggrepel")

df <- data.frame(
  x = c(1,2),
  y = c(2,4),
  lab = c("italic('Italic Text')", "Normal"))

ggplot(df, aes(x, y, label = lab)) +
    geom_point() +
    geom_text_repel(parse = T)

但是,我一直无法使用相同的方法来获取删除线文本。

df$lab = c("strike('Strikethrough Text')", "Normal")

ggplot(df, aes(x, y, label = lab)) +
    geom_point() +
    geom_text_repel(parse = T)

如评论中所述,plotmath 无法处理删除线。然而,我们可以用 phantomunderline.

做一些小技巧
library(tidyverse)

df <- data.frame(
  y = c(1, 2),
  lab = c("italic('Italic Text')", "Strikethrough"),
  do_strike = c(FALSE, TRUE)
)

wrap_strike 获取文本并将其包装在 phantom 中,使其不可见。对于删除线文本,它会添加一个 underline.

wrap_strike <- function(text, do_strike) {
  text <- glue::glue("phantom({text})")
  ifelse(do_strike, glue::glue("underline({text})"), text)
}

如果我们微调新文本的 y 位置,下划线将变为删除线。

ggplot(df, aes(1, y, label = lab)) +
  geom_point() +
  geom_text(parse = TRUE, hjust = 0) +
  geom_text(
    data = mutate(df, lab = wrap_strike(lab, do_strike)),
    parse = TRUE,
    hjust = 0,
    vjust = 0.1
  )

使用 Unicode 长罢工覆盖怎么样?

R Script
# Long strikethru test
# Unicode Character 'COMBINING LONG STROKE OVERLAY' (U+0336)

library("tidyverse")

# Keep 30 first rows in the mtcars natively available dataset
data <- head(mtcars, 30)

name <- "Strikethrough"
name_strk <- str_replace_all(name, "(?<=.)", "\u0336")

# Add one annotation
ggplot(data, aes(x=wt, y=mpg)) +
  geom_point() + # Show dots
  geom_label(
    label= name_strk,
    x=4.1,
    y=20,
    label.padding = unit(0.55, "lines"), # Rectangle size around label
    label.size = 0.35,
    color = "black",
    size = 4,
    fill="white"
  )