Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

Please pardon my ignorance if this is a simple question, but I can't seem to figure out how to underline any part of a plot title. I'm using ggplot2.

The best I could find was annotate("segment") done by hand, and I have created a toy plot to illustrate its method.

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

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

Alternatively, as BondedDust points out in the comments, you can avoid the paste() call entirely, but watch out for the for:

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

Or another, even shorter approach suggested by baptiste that doesn't use expression, paste(), or the many tildes:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...