如何在绘图标题或标签中添加下划线?

17

我似乎无法弄清楚如何在图表标题的任何部分添加下划线。

我找到的最好办法是手工标记("segment"),并且我创建了一个玩具图表来说明它的方法。

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)

enter image description here

使用基本R中的underline()函数

涉及到图上节点上下方的线条

使用plotmath并提供了一种解决方法,但没有帮助

1个回答

20

试试这个:

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))

如果使用 expression,为什么不使用 expression(Oh~how~I~wish~for ~underline(underlining))。不需要经常令人困惑的 plotmath paste() 调用。 - IRTFM
@BondedDust 我不知道那种方法。当我尝试时,我收到一个错误:Error: unexpected '~' in: "ggplot(df, aes(x = x, y = y)) + geom_point() + ggtitle(expression(Oh~how~I~wish~for ~"。我做错了吗? - Jota
4
该死,是 F 单词搞的鬼。R 解析器看到 "for" 就会去查找索引。这机器真蠢!尝试使用 expression(Oh~how~I~wish~'for'~underline(underlining))。使用 "in" 单词也会出现同样的解析错误。 - IRTFM
7
ggtitle(~"哦,我多么渴望"*underline(加下划线)) 可能是最简单的。 - baptiste
太好了!我已经接受了答案(并感谢所有的评论)。您能否解释一下波浪线~和星号*的用法?谢谢。 - lawyeR
1
@lawyeR 它们是 plotmath 分隔符。波浪号是空格分隔符/连接器,星号是非空格分隔符/连接器。它们可以很好地连接表达式和文本,使其更易读。有关更多信息/文档,请询问像 baptiste 这样的人(使用 @baptiste),他是真正的绘图大师。实际上,我不知道相关文档在哪里。 - Jota

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接