2

Is it possible to add strikethrough to some geom_text/geom_text_repel labels?

This question mentioned that you can italicise a label using the following:

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)

enter image description here

However, I've been unable to use the same method to get strikethrough text.

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

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

enter image description here

Paul
  • 8,734
  • 1
  • 26
  • 36
  • Possible duplicate of https://stackoverflow.com/questions/20315962/r-text-formatting-of-plot-label-text-strikethrough ? – Indrajeet Patil Feb 16 '18 at 04:02
  • That question is applying formatting to the axis, not the labels. If it is possible to use the same method on `geom_text_repel` labels, please let me know. – Paul Feb 16 '18 at 04:09
  • it is using `plotmath` and there is no `strike` command. have a look at `demo(plotmath)` – drmariod Feb 16 '18 at 06:14

2 Answers2

1

What about using a Unicode long strike overlay?

enter image description here

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"
  )
ixodid
  • 2,180
  • 1
  • 19
  • 46
0

As was mentioned in the comments, plotmath cannot handle strikethrough. However, we can do some tricks with phantom and underline.

library(tidyverse)

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

wrap_strike takes the text and wraps it in phantom which makes it invisible. For strikethrough text, it adds an underline.

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

If we nudge the y position of the new text, the underlines become strikethrough.

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
  )

strikethrough

Paul
  • 8,734
  • 1
  • 26
  • 36