简体   繁体   English

如何使用变量使用 latex2exp 注释 ggplot2 plot?

[英]How to annotate a ggplot2 plot with latex2exp using variables?

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} .我试图获得像y=10e^{20x}这样的 label 。 Is it possible with latex2exp or is there better way? latex2exp有可能还是有更好的方法?

Thanks谢谢

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

One way to do it with latex2exp would be to use sprintf to construct the LaTeX string:使用latex2exp的一种方法是使用sprintf构造 LaTeX 字符串:

p1 + annotate("label", x = 4, y = 25, label = TeX(sprintf("$y = %d e ^{%dx}$", alpha, beta)))

You can use bquote() or paste() , and set the argument parse=TRUE您可以使用bquote()paste() ,并设置参数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)代表 package (v0.3.0) 于 2020 年 4 月 23 日创建

Hopes helpful for you.希望对你有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM