title: How to write an equation with a variable in legend?
body: <p>I am trying to write an equation like "R^2=0.00575" in the legend, and the number 0.00575 can be embedded in the legend automatically. Here is an example.</p>
  
  <pre><code>set.seed(100)
  x=rnorm(100)
  y=1:100
  fit=lm(y~x)
  R_squared=format(summary(fit)$r.squared,digits = 3)
  plot(x,y,type="l")
  legend("topleft",legend =expression(R^{2}~"="~R_squared),bty = "n")
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/5Gyhw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5Gyhw.png" alt="enter image description here"></a></p>
  
  <p>As the figure shows, the variable <code>"R_squared"</code> is not embedded in the equation. Is there any solution? Thanks.</p>