13

Is there any way to get control characters for text strings, e.g. "\n" for newline evaluated inside a plotmath expression, or vice versa. In the following example, I would like to combine:

  • some character text
  • text control character (newline)
  • substitute a variable name
  • include a plotmath expression

After reading this question I can get most of the way there with substitute, but the newline character is not evaluated. I am now going round in circles and confusing myself with plotmath, parse, bquote and substitute. In the help page for plotmath it says

Control characters (e.g. \n) are not interpreted in character strings in plotmath, unlike normal plotting.

Does this mean it really is impossible?

lab = "some data"
form = "Exponential"
x = 1:10
y = x^2


plot( x , y , type = "b" )
title( main = substitute( paste( "Plot of " , phi , " of: "  , lab , "\nFunctional form: " , form ) , list(lab = lab , form = form ) ) , adj = 0 )

enter image description here

3 Answers 3

12

As you have figured plotmath does not support newlines within, but you can use mtext with bquote, to write each line. For example I create a list of lines :

Lines <- list(bquote(paste( "Plot of " , phi , " of: "  , .(lab))),
              bquote(paste("Functional form: " , .(form)))

mtext(do.call(expression, Lines),side=3,line=1:0)

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Your solution works just perfectly! Thank you so much for wading through the quagmire of bquote and math/text expressions for me! +1
5

For the sake of completeness, here's another solution using unicode and no expressions (adapted from here and here):

plot(x, y, type="b")
title(main=paste("Plot of \u03A6 of:", lab, "\nFunctional form:", form), adj=0)

enter image description here

3 Comments

+1 Thanks. This is a nice straightforward solution. I didn't even know it was possible to include unicode characters like this. If it were possible to split credit for accepted answers here I would. Thanks!
As a bit of warning though, some platform/devices don't render all unicode character properly, so it is a good thing that you have agstudy and baptiste solutions as well to fall back on when it happens. See this blog post for some additional tips.
Ah, thank you for the heads up. You will have probably saved me some additional future headaches when I can't recreate your solution. Thanks again, and thanks for the link.
4

if you use grid graphics, then the following grob can be useful to space the lines according to their height,

library(devtools)
source_gist(2732693)
grid.expr(as.expression(Lines))

(using agstudy's Lines)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.