1

Here is my sample code.

library(ggplot2)
library(latex2exp)
p1 <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
alpha=10
beta=20
p1 + annotate("label", x = 4, y = 25, label = TeX("$y = alpha e ^{betax}$"))

I was trying to get a label like y=10e^{20x}. Is it possible with latex2exp or is there better way?

Thanks

0

3 Answers 3

2

One way to do it with latex2exp would be to use sprintf to construct the LaTeX string:

p1 + annotate("label", x = 4, y = 25, label = TeX(sprintf("$y = %d e ^{%dx}$", alpha, beta)))
Sign up to request clarification or add additional context in comments.

Comments

1

Try TeX(paste("$y = ", alpha, "e ^{", beta, " x}$"))?

1 Comment

Works but I get a warning: is.na() applied to non-(list or vector) of type 'expression'
1

You can use bquote() or paste() , and set the argument parse=TRUE

library(ggplot2)
p1 <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
alpha=10
beta=20
p1 + 
  annotate("label", 
           x = 4, y = 25, 
           label = list(bquote(y==.(alpha)*e^{.(beta)*x})), parse= TRUE
  )


p1 + 
  annotate("label", 
           x = 4, y = 25, 
           label = paste("y==", alpha, "*e^", "{", beta, "*x}"), parse= TRUE
  )

Created on 2020-04-23 by the reprex package (v0.3.0)

Hopes helpful for you.

2 Comments

A while ago I tried label = bquote(y==.(alpha)*e^{.(beta)*x}). The result is perfect except that a redundant pair of brackets appears after the equation. Do you have any idea why?
@MatthewHui Sorry, I have no idea why. And it requires coerce your label to a list, such as list(bquote(y==.(alpha)*e^{.(beta)*x}))

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.