如何在绘图标题或标签中为文本加下划线? (ggplot2)

How to underline text in a plot title or label? (ggplot2)

如果这是一个简单的问题,请原谅我的无知,但我似乎无法弄清楚如何在情节标题的任何部分下划线。我正在使用 ggplot2.

我能找到的最好的是 annotate("segment") done by hand,我创建了一个玩具图来说明它的方法。

df <- data.frame(x = 1:10, y = 1:10)

rngx <- 0.5 * range(df$x)[2]  # store mid-point of plot based on x-axis value
rngy <- 0.5 * range(df$y)[2]  # stores mid-point of y-axis for use in ggplot

ggplot(df, aes(x = x, y = y)) + 
  geom_point() +
  ggtitle("Oh how I wish for ..." ) +
  ggplot2::annotate("text", x = rngx, y = max(df$y) + 1, label = "underlining!", color = "red") +
  # create underline:
  ggplot2::annotate("segment", x = rngx-0.8, xend = rngx + 0.8, y= 10.1, yend=10.1)

uses bquote(underline() with base R

pertains to lines over and under nodes on a graph

uses plotmath and offers a workaround, but it didn't help

试试这个:

ggplot(df, aes(x = x, y = y)) + geom_point() +
  ggtitle(expression(paste("Oh how I wish for ", underline(underlining))))

或者,正如 BondedDust 在评论中指出的那样,您可以完全避免 paste() 调用,但要注意 for:

ggplot(df, aes(x = x, y = y)) + geom_point() +
  ggtitle(expression(Oh~how~I~wish~'for'~underline(underlining)))

或者 baptiste 建议的另一种更短的方法,它不使用 expressionpaste() 或许多波浪号:

ggplot(df, aes(x = x, y = y)) + geom_point() +
  ggtitle(~"Oh how I wish for "*underline(underlining))