1

ENV

R 3.3.2

I plot figures in a loop. And I want set title in each iteration.

code as below:

beta1 = 2
alpha1 = 3
main = expression(paste((beta == bquote(.(beta1))) * " my strings " * (alpha == bquote(.(alpha1))) * " my second strings)),

expression function to ensure plot math symbols and paste function to combine math symbol and strings together. Now I want set beta value in each iteration. I tried to use bquote follow using-an-expression-in-plot-text-printing-the-value-of-a-variable-rather-than-its-name but it not works.

My Expected value should:

β = 1 my strings α = 3 my second strings

Any ideas or alternative ways or any advice? Thanks.

Community
  • 1
  • 1
Nick Dong
  • 3,638
  • 8
  • 47
  • 84

1 Answers1

2

Make the pasting inside the bquote() function:

for(iter in 1:3){
  txt = bquote(beta == .(paste(iter, "my strings")))
  print(plot(0, 0 , main = txt, type = "n"))
  text(0, 0, txt)
}

Edit: In case you also want to show the text within the plot and not only as the title.

Tonio Liebrand
  • 17,189
  • 4
  • 39
  • 59
  • The value of `beta1` has been plotted. But `beta` is not shown as `β`. It did not plot math. – Nick Dong Feb 09 '17 at 10:45
  • I cant reproduce that error on Rstudio 1.0.136, R 3.3.2. Neither in R nor in RStudio. As you use `main= ` you are talking about the title or do you want the text in your plot? – Tonio Liebrand Feb 09 '17 at 11:13
  • I added the text within the plot as well, if anything. – Tonio Liebrand Feb 09 '17 at 11:24
  • Yes. It works. I use `Rscript` to run script and plot it to pdf and It shows correctly. But when I use R studio and R Gui or Rscript plotting to png, it not works. That might something wrong with my system. – Nick Dong Feb 09 '17 at 11:35
  • Yes I want plot title. But plotting text is same thing. Now (`main= bquote(paste((beta == .(beta1)) * " my strings " * (alpha == .(alpha1)) * " my second strings"))`) Just replace `expression` by `bquote`. It works(still works in Rscript with pdf). [bquote will create an expression](http://stackoverflow.com/questions/15074127/use-expression-with-a-variable-r?rq=3) Thanks @BigDataScientist – Nick Dong Feb 09 '17 at 11:51