【问题标题】:How do I include strikethrough text in geom_text_repel or geom_text labels for ggplot?如何在 ggplot 的 geom_text_repel 或 geom_text 标签中包含删除线文本?
【发布时间】:2018-07-26 22:50:24
【问题描述】:

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

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

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)

【问题讨论】:

  • 那个问题是将格式应用于轴,而不是标签。如果可以在geom_text_repel 标签上使用相同的方法,请告诉我。
  • 它正在使用plotmath 并且没有strike 命令。看看demo(plotmath)

标签: r text ggplot2 ggrepel


【解决方案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"
  )

【讨论】:

    【解决方案2】:

    正如 cmets 中提到的,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
      )
    

    【讨论】:

      猜你喜欢
      • 2017-05-22
      • 2022-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-11
      • 1970-01-01
      • 2022-11-25
      • 2017-03-25
      相关资源
      最近更新 更多