2

是否可以添加删除线给一些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)

在此处输入图像描述

4

2 回答 2

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"
  )
于 2020-12-20T00:19:45.663 回答
0

正如评论中提到的,plotmath无法处理删除线。phantom但是,我们可以用和做一些技巧underline

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
  )

删除线

于 2020-11-18T02:02:16.787 回答