簡體   English   中英

如何在 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)

在此處輸入圖片說明

使用 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"
  )

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

刪除線

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM