Giter Club home page Giter Club logo

latex2exp's Introduction

R-CMD-check

latex2exp

latex2exp is an R package that lets you use LaTeX in plots. It parses and converts LaTeX to R’s custom plotmath expressions. You can read the full documentation on the package’s website.

Expressions returned by latex2exp can be used to create formatted text and mathematical formulas and symbols to be rendered as axis labels, annotations, legends, titles, etc. throughout R’s plotting system.

Installation

Install this package from CRAN:

install.packages('latex2exp')

You can also install the development version from GitHub using devtools:

devtools::install_github('stefano-meschiari/latex2exp')

Usage

The TeX function takes a LaTeX string, parses it, and returns the closest plotmath expression suitable for use in graphics. The return value of TeX() can be used anywhere a plotmath expression is accepted, including plot labels, legends, and text for both base graphics and ggplot2.

Here’s a simple example:

# Use raw strings, no need to escape backslashes.
TeX(r"(\textbf{Euler's identity} is $e^{i\pi} + 1 = 0$.)")

In this example, \textbf{} is used to mark a fragment of text as bold, $ introduces inline math mode, ^{} typesets its contents as superscript, and \pi typesets the letter π.

Starting with R 4.0, it is recommended to use the new raw string literal syntax (see ?Quotes). The syntax looks like r"(...)", where ... can contain any character sequence, including \.

Another option is to escape the backslash character (\) for LaTeX commands, such that the command will be written as \\command rather than \command. This will also work on versions of R older than 4.0:

# Equivalent to the previous code fragment.
# Use regular strings, but escape the backslashes.
TeX("\\textbf{Euler's identity} is $e^{i\\pi} + 1 = 0$.")

You can quickly preview what a translated LaTeX string would look like by using plot:

plot(TeX(r'(A $\LaTeX$ formula: $\frac{2hc^2}{\lambda^5}\frac{1}{e^{\frac{hc}{\lambda k_B T}} - 1}$)'), cex=2, main="")

The following example shows plotting in base graphics:

x <- seq(0, 4, length.out=100)
alpha <- 1:5

plot(x, xlim=c(0, 4), ylim=c(0, 10), 
     xlab='x', ylab=TeX(r'($\alpha  x^\alpha$, where $\alpha \in \{1 \ldots 5\}$)'), 
     type='n', main=TeX(r'(Using $\LaTeX$ for plotting in base graphics!)', bold=TRUE))

for (a in alpha) {
  lines(x, a*x^a, col=a)
}

legend('topleft', 
       legend=TeX(sprintf(r'($\alpha = %d$)', alpha)), 
       lwd=1, 
       col=alpha)

This example shows plotting in ggplot2:

x <- seq(0, 4, length.out=100)
alpha <- 1:5
data <- map_df(alpha, ~ tibble(v=.*x^., x=x, alpha=.))

p <- ggplot(data, aes(x=x, y=v, color=as.factor(alpha))) +
    geom_line() + 
    ylab(TeX(r'($\alpha  x^\alpha$, where $\alpha \in 1\ldots 5$)')) +
    ggtitle(TeX(r'(Using $\LaTeX$ for plotting in ggplot2. I $\heartsuit$ ggplot!)')) +
    coord_cartesian(ylim=c(-1, 10)) +
    guides(color=guide_legend(title=NULL)) +
    scale_color_discrete(labels=lapply(sprintf(r'($\alpha = %d$)', alpha), TeX)) 
    # Note that ggplot2 legend labels must be lists of expressions, not vectors of expressions

print(p)

Here are a few examples of what you can do with latex2exp:

latex2exp_examples(cex=0.9)

Supported LaTeX commands

Table of supported LaTeX

latex2exp's People

Contributors

elobove avatar jan-glx avatar stefano-meschiari avatar wzel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

latex2exp's Issues

Using "\left(" with "\right." - bgroup is not correctly constructed

In LaTeX one can construct a large open parenthesis with \left(\frac{M}{L}\right.. Using this with TeX is possible and gives:

TeX("$\\left(\\frac{M}{L}\\right.$")
#> expression(`$\left(\frac{M}{L}\right.$` = 
#>            paste("", "", bgroup("(", paste("", frac(paste("M"), paste("", "L")), ""))))

It is not possible to use this as the bgroup is missing the "closing" dot. The correct code would be:
expression(bgroup("(", frac("M", "L"), ".")) (I removed unneccessary paste and empty strings, for emphasis on the ".").

plot.new()
plot.window(c(0,3), c(0,1))
text(0, 0.5, latex2exp::TeX("$\\left(\\frac{M}{L}\\right)$")) # works
text(1, 0.5, latex2exp::TeX("$\\left(\\frac{M}{L}\\right.$")) 

Error in bgroup("(", paste("", frac(paste("M"), paste("", "L")), "")) :
invalid group specification

text(2, 0.5, expression(bgroup("(", frac("M", "L"), "."))) # works

grafik

break line

How to do break in line? For example I want to get:
This is first line of plot title
and this is the next

Entry point not found

I installed the latest latex2exp manually from the binary available in CRAN, in a Windows computer without internet (I am working in a secure lab environment). I am using R 3.3.1, with RGui (crap, I know, but I am not an administrator and change requests are slow). When I load the package, I get a pop-up message saying:

The procedure entry point DATAPTR could not be located in the dynamic link library R.dll.

After accepting the message, the R console says:

Error in inDL(x, as.logical(local), as.logical(now), ... ) :
unable to load shared object '//path/to/my/local/library/stringi/libs/x64/stringi.dll :
LoadLibrary failure: The specified procedure could not be found.

Not sure what is the problem, as the file stringi.dll is in the aforementioned folder. The file is the original from the package .zip file.

I manually installed other packages and dependencies (like ggplot2) and they load fine, so it seems to be an issue of latex2exp. Hence my post here. Any idea?

output options not consistent between TeX and .parseTeX

Using Tex, the possible outputs options in doc are c("expression", "text", "ast"). From what I observed, "expression" and "text" return the same result.

While looking at the function .parseTeX, the possible returns are triggered with the following code :

  if (output[1] == "ast") 
    return(root)
  str <- toString(root)
  exp <- tryCatch(parse(text = str), error = function(e) {
    cat("Original string: ", original, "\n")
    cat("Parsed expression: ", str, "\n")
    stop(e)
  })
  if (output[1] == "character") {
    return(str)
  }
  else return(exp)

Does this mean that the TeX return options are c("expression", "character", "ast") and not c("expression", "text", "ast") ?
I expect so, because when using TeX(sprintf("$V_l = %.4f$", vl), output = c('expression')) I get a string.

Is it possible to change the documentation and the code ?

Round brakets after exponent trigger undue exponentiation

Hi,

the commands

plot(TeX(r"($B^a(b)$)"))
plot(TeX(r"($B^{a}(b)$)"))
plot(TeX(r"($B^a (b)$)"))
plot(TeX(r"($B^{a} (b)$)"))

all result in the "(b)" string being unduly positioned as an exponent. I could not find a way to circumvent that, unless adding a space with "," in between.

Greetings!

Alberto

LaTeX hyperlinks

Would it be possible to incorporate \ref so that geom_text could link to other parts of a pdf?

The symbol of absolute value in TeX()?

The code TeX("$\\hat{|\\rho|}$") gives the following error:

Original string:  $\hat{|\rho|}$ 
Parsed expression:  paste('','',hat(paste('|',rho|,,,)),'') 
Error in parse(text = str) : <text>:1:31: unexpected ','
1: paste('','',hat(paste('|',rho|,

TeX() output arg choice should be "character" not "text"

Thank you for a wonderful package!! Just a minor bug.

The function signature for TeX() is:

function (string, output = c("expression", "text", "ast")) 

... but the signature for .parseTeX() is:

function (string, output = c("expression", "character", "ast")) 

Passing output = "text" to TeX() therefore fails to produce the desired result (but passing output = "character" does).

output = "text" inconsistent with output = "character"

According to the help file, output = "text" returns a string, but it actually returns an expression the same as output = "expression". It should be output = "character" in the help file or the function should be changed so output = "text" works.

closing braces

Closing braces don't seem to show up for me (R 3.6.1 on ubuntu):

library(latex2exp)
plot(1:10, main=TeX("$\{ x \}$") )

Assistance Needed with R and latex2exp for Latex Conversion

Dear Dr. Meschiari,

I apologize for any inconvenience with the following message regarding an issue I'm having with using latex2exp.

My name is Raffaele Vardavas, and I recently came across your insightful post that describes the utilization of your latex2exp package, particularly emphasizing the significance of employing raw strings. Your example, where "\Psi" was transformed into r"(\Psi)", greatly clarified this process.

Nonetheless, I am encountering challenges in handling the case when my string is a variable. For example, the following command works fine:

latex2exp::TeX(r'($\tilde{\alpha}_k$)')

but what if my input variable is "\tilde{\alpha}_k" such as in the following code:

x<-"\tilde{\alpha}_k"
parsed_expr <- paste0("r'($",x,"$)'")
latex2exp::TeX(x)

this does not give me the same output. I need to process a vector read from an excel spreadsheet, where each element x is a LaTeX expression and convert them to a vector or list that contains the elements latex2exp::TeX(x) as my outputs. The issue is very much linked to the single backslash, and all my attempts in getting a working solution by asking chatGPT end with frustrating failures.

Any guidance or insight you can provide regarding the conversion would be greatly appreciated.

Thanks!
Raff

Create specialized text geoms for ggplot2 and ggrepel

Currently, using TeX() with ggplot2 to plot formatted text is markedly different from base graphics. With base graphics, calling

text(TeX(r"($\alpha + \beta$)"))

will plot the expression in the current plot.

In ggplot, the following will work:

ggplot(mtcars, aes(x=wt, y=mpg)) + 
geom_point() + 
xlab(TeX(r"(Car \textbf{weight})")) + 
ylab(TeX(r"(Car \textbf{fuel efficiency})")) # use the return value of TeX directly

but in the geoms like geom_text, geom_label, and annotate that take a label aesthetic, the input vector for the label aesthetic is expected to be of type character, rather than of type expression. In order to plot formatted text and formulas, the user is expected to pass a character representation of the plotmath expression and use the parameter parse=TRUE:

ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() +
annotate("text", x = 4, y = 25, label = "alpha+beta", parse=TRUE)

(note that in some cases, the geom will accept an expression, but will throw a warning).

The only way to use TeX in these situations is to make it return a character value and set parse to TRUE, e.g.:

ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() +
annotate("text", x = 4, y = 25, label = TeX(r"(\alpha+\beta)", parse=TRUE)

I propose to add the functions: geom_text_tex, geom_label_tex, and annotate_tex. These functions will forward to the underlying ggplot functions, and set the appropriate parameters for the user, such that:

ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() +
annotate_tex(x = 4, y = 25, label = r"(\alpha+\beta)")

will automatically parse TeX, turn it into an expression, and forward it to annotate with parse=TRUE.

Remove space after decimal point

For some reason a blank space is automatically added after a decimal point and I don't understand why.
For example, see:

TeX("3.3")
># expression(`3.3` = paste("3", ". 3"))

when it should produce

># expression(`3.3` = paste("3", ".3"))

See it in a plot:

plot(1:4, 1:4, main = TeX("3.3"))

Any way to fix this?
Thanks.

latex2exp not rendering comma separated number correctly

I use latex2exp to render a simple expression in an R figure in the legend text. I want to use "," as the decimal separator. When I do so, the next digit is not rendered, so "0,05" becomes "0,5" in the figure -- both as displayed in R Studio and in exported PDF.

A minimal working example is:

library(latex2exp)
plot(TeX("$h^2=0,05$")) # <--- this does not render correctly

SessionInfo() is:

> sessionInfo()
R version 4.2.2 (2022-10-31 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19045)

Matrix products: default

locale:
[1] LC_COLLATE=Danish_Denmark.utf8  LC_CTYPE=Danish_Denmark.utf8    LC_MONETARY=Danish_Denmark.utf8 LC_NUMERIC=C                   
[5] LC_TIME=Danish_Denmark.utf8    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] latex2exp_0.9.6 mvtnorm_1.1-3  

loaded via a namespace (and not attached):
 [1] compiler_4.2.2  magrittr_2.0.3  cli_3.5.0       tools_4.2.2     glue_1.6.2      rstudioapi_0.14 vctrs_0.5.1     stringi_1.7.8  
 [9] stringr_1.5.0   lifecycle_1.0.3 rlang_1.0.6     fortunes_1.5-4 

R is running under R-Studio 2022.12.0 Build 353.

Expected behavior
I expected to see a rendering of "h-squared=0,05"

Actual behavior
What I see on screen and in exported PDF is:
h2equal005

Workaround
Changing the code to

library(latex2exp)
plot(TeX("$h^2$=0,05")) # <--- this renders correctly

produces the expected output. Thus the problem easy to work around, but I think the behavior of the "TeX" function is not desirable.

Best wishes

Fix parsing of numbers

latex2exp("$p = 0.05$") produces the wrong output (p = 0.5) because of incorrect parsing of numbers.

Reported by Carlos Menezes via email.

Error in `stop_vctrs()` ! Input must be a vector, not an environment.

Describe the bug
I run the script

TeX('$\\alpha^\\beta$')

and it raise Exception:

Error in `stop_vctrs()`:
! Input must be a vector, not an environment.
Traceback:

TeX("$\\alpha^\\beta$")
parse_latex(input)
validate_input(latex_string)
str_detect(latex_string, fixed(possible_slash_pattern))
check_lengths(string, pattern)
vctrs::vec_size_common(string = string, pattern = pattern, replacement = replacement, 
 .     .call = error_call)
stop_scalar_type(.Primitive("quote")(<environment>), "")
stop_vctrs(msg, "vctrs_error_scalar_type", actual = x)
abort(message, class = c(class, "vctrs_error"), ...)
signal_abort(cnd, .file)

To Reproduce

  1. Paste the output of sessionInfo() (this should show, at minimum, the version of R, the platform, and the architecture you are running on)
R version 3.5.0 (2018-04-23)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: CentOS Linux 7 (Core)

Matrix products: default
BLAS: /home/wyh/anaconda3/lib/R/lib/libRblas.so
LAPACK: /home/wyh/anaconda3/lib/R/lib/libRlapack.so

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] latex2exp_0.9.6

loaded via a namespace (and not attached):
 [1] fansi_0.5.0     utf8_1.2.2      digest_0.6.15   crayon_1.3.4   
 [5] IRdisplay_0.5.0 repr_0.15.0     lifecycle_1.0.3 jsonlite_1.5   
 [9] magrittr_2.0.1  evaluate_0.15   pillar_1.6.4    stringi_1.7.12 
[13] rlang_1.1.1     cli_3.6.1       uuid_0.1-2      ellipsis_0.3.2 
[17] vctrs_0.3.8     IRkernel_1.1.1  tools_3.5.0     stringr_1.5.0  
[21] glue_1.6.2      fastmap_1.1.0   compiler_3.5.0  base64enc_0.1-3
[25] htmltools_0.5.2 pbdZMQ_0.3-3   
  1. Include a short snippet of code I can use to reproduce the problem. You can use reprex::reprex() to quickly prepare a reproducible example.

  2. What environment are plotting from? (e.g. RStudio, the R Console, Visual Studio Code, etc.)
    I use jupyter jupyter_server : 1.24.0, anaconda ,centos7.

  3. If the bug comprises unexpected visual output from TeX(), please paste a screenshot of what you see on your system. You can plot a single TeX expression by running

# example
library(latex2exp)
plot(TeX(r"($\alpha + \beta$)")) # <-- this doesn't render correctly

It raise Exception

Error in parse(text = x, srcfile = src): <text>:3:11: unexpected string constant
library(latex2exp)
plot(TeX(r"($\alpha + \beta$)"
             ^
Traceback:

Italics in math mode and minus sign

To match TeX better, Latin characters should be in italics by default in mathmode, and $-$ should give a minus sign instead of a hyphen.

Otherwise, this package is perfect.

Possibility to include \vdots and \ddots

I was annotating a plot that was build using ggplot2. I tried to use TeX($\\vdots$) and TeX($\\ddots$) but these options are not supported by latex2exp.

Can you include them in latex2exp?

Best wishes and thank you for building the package latex2exp

Type stability of new parser

Hi @stefano-meschiari,

Thank you very much for this awesome package! After installing v0.9.0, I ran into problems with my own functions that build on TeX(). I could pin down the problem easily, but I think it might be worth discussing whether or not something should be changed in latex2exp, too.

Here is the issue: If an empty character is passed (i.e., TeX("")), the new return value in version 0.9.0 has length zero, while in earlier versions it was an empty expression (i.e., the same as from expression("")). I believe the old behaviour is preferable (and "right") because it makes the output more predictable and length("") equals 1 in R.

What do you think?

Best regards,
Marius

Missing spaces when plotting from VSCode

Hello,

I'm not sure whether this is a VSCode, a radian, or a latex2exp problem. It's probably the former but the latex2exp community is here, so here it is:

Running the exact same code from different environments does not yield the same result. As an example, I run the following vignette example:

library(latex2exp)
plot(TeX(r'(A $\LaTeX$ formula: $\frac{2hc^2}{\lambda^5}\frac{1}{e^{\frac{hc}{\lambda k_B T}} - 1}$)'), 
     cex=2, main="")
  • Within RStudio: it works as expected
  • Within radian or "normal" R executable in the terminal: it works as expected
  • Within radian in VSCode: all spaces are trimmed, there are no spaces between words. See image below.
  • Within "normal" R executable in VSCode: it works as expected

image

Since I work in VSCode using radian, this is driving me nuts... I need to manually add them using \: or the likes.

Thanks in advance for your help!

r$> sessionInfo()

R version 4.2.2 (2022-10-31)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Monterey 12.6

Matrix products: default
BLAS:   /Library/Frameworks/R.framework/Versions/4.2/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.2/Resources/lib/libRlapack.dylib

locale:
[1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils    
[5] datasets  methods   base     

loaded via a namespace (and not attached):
[1] compiler_4.2.2 cli_3.4.1     
[3] jsonlite_1.8.3 rlang_1.0.6   

Consecutive Spaces are not working in v0.9.0

Hi, Thank you for your excellent package. It has helped me a lot. Following Code does not work in version 0.9.0. However I have reverted to version 0.5.0 and it works in that.

# #ERROR in latex2exp_0.9.0
c(TeX(r'($\,\,\mu - 3 \sigma$)'))
#
#Error in value[[3L]](cond) : Error while converting LaTeX into plotmath.
#Original string: $\,\,\mu - 3 \sigma$
#Parsed expression: phantom() * phantom(.) *  * phantom(.) * mu - 3*sigma
#Error in str2expression(rendered): <text>:1:27: unexpected '*'
#1: phantom() * phantom(.) *  *
#
# # This modification works in v0.9.0
c(TeX(r'($\,\mu - 3 \sigma$)'))
# #Works in latex2exp_0.5.0
c(TeX(r'($\,\,\mu - 3 \sigma$)'))
#expression(`$\,\,\mu - 3 \sigma$` = paste("", "", 
#    paste(" "), "", paste(" "), "", mu, 
#    , , , phantom() - phantom(), "3", "", sigma, 
#    , , , ""))
#

Edit: Sorry, forgot to add SessionInfo

# #SessionInfo after reverting to version 0.5.0
sessionInfo()
#R version 4.1.2 (2021-11-01)
#Platform: x86_64-w64-mingw32/x64 (64-bit)
#Running under: Windows 10 x64 (build 19042)
#
#Matrix products: default
#
#locale:
#[1] LC_COLLATE=English_India.1252  LC_CTYPE=English_India.1252    LC_MONETARY=English_India.1252 LC_NUMERIC=C                  
#[5] LC_TIME=English_India.1252    
#system code page: 65001
#
#attached base packages:
#[1] stats     graphics  grDevices datasets  utils     methods   base     
#
#other attached packages:
#[1] latex2exp_0.5.0
#
#loaded via a namespace (and not attached):
# [1] compiler_4.1.2  magrittr_2.0.2  bookdown_0.24   fastmap_1.1.0   cli_3.1.1       htmltools_0.5.2 tools_4.1.2    
# [8] yaml_2.2.2      stringi_1.7.6   rmarkdown_2.11  knitr_1.37      stringr_1.4.0   xfun_0.29       digest_0.6.29  
#[15] rlang_1.0.0     evaluate_0.14 

Edit 2:
And now I have realised that this might be a duplicate of what you have already handled in the closed issue given Here

white space causes unexpected behaviour

Awesome work, this package is going to be really useful!

I noticed that whitespace in equations caused some unexpected behaviour. In the following code, the top two panels are as expected and the bottom two aren't:

par(mfrow = c(2, 2))

# as expected
plot.new()
text(0.5, 0.5, latex2exp('$\\frac{1}{x^2}$'), cex = 5)

# as expected
plot.new()
text(0.5, 0.5, latex2exp('$2^{\\frac{1}{x^2}}$'), cex = 5)

# power dies not appear
plot.new()
text(0.5, 0.5, latex2exp('$\\frac{1}{x ^ 2}$'), cex = 5)

# power appears outside the fraction
plot.new()
text(0.5, 0.5, latex2exp('$2^{\\frac{1}{x ^ 2}}$'), cex = 5)

A simple fix might be to remove any whitespace within equations. I'd have a bash and submit a PR, but I'm unfamiliar with stringr so would probably take me forever

Error with two 'leq' in latex2exp::TeX()

I need to display a text containing two consecutive "less or equal than" symbols in a ggplot. I manage to display one symbol but not two. This bug does not occur with 'less than' symbols.

# NON OK
(text1 <- paste0("for $0\\leq t \\leq t_{c}$"))
(textFormat <- latex2exp::TeX(text1))

# OK : example with a first symbol 'leq' and a second '<'
(text1 <- paste0("for $0\\leq t < t_{c}$"))
(textFormat <- latex2exp::TeX(text1))

# OK : example with a first symbol '<' and a second 'leq'
(text1 <- paste0("for $0<t\\leq t_{c}$"))
(textFormat <- latex2exp::TeX(text1))

# OK : example with two symbols '<'
(text1 <- paste0("for $0<t<t_{c}$"))
(textFormat <- latex2exp::TeX(text1))

# plot
y <- seq(max(length(text)), 0.5, length.out = length(text))
ggplot() +
  annotate("text", x = -1, y = y, size=4.5, hjust = 0, label = paste(textFormat), parse = TRUE) +
  coord_cartesian(xlim = c(-1, 1), ylim = c(-1,max(length(text))+1))

The error send is:

Erreur dans value[[3L]](cond) : Error while converting LaTeX into plotmath.
Original string: for $0\leq t \leq t_{c}$
Parsed expression: 'for '*0 <= t <= t[c]
Error in str2expression(rendered): <text>:1:15: '<=' inattendu(e)
1: 'for '*0 <= t <=
                  ^

I have tried many things to no avail. I would like some help to solve my problem

in.na(x) warning when using TeX with ggplot2

When I use TeX inside of annotate in ggplot2 I get the following warning:

Warning message:
In is.na(x) : is.na() applied to non-(list or vector) of type 'expression'

Is there a way to get this warning to go away?

Here is a reproducible example:

ggplot(data.frame(x = c(-3, 3))) + 
      aes(x = x) + 
      stat_function(fun = dnorm, n = 100, args = list(mean = 0, sd = 1)) + 
      annotate("text", x = -2, y = 0.2, size = 7, 
        label = latex2exp::TeX("$\\textit{N}(0,1)$"), parse = TRUE)

Line break in TeX()?

I would like to add a line break in the plot title using the LaTeX command \newline, however it didn't produce the figure as expectation.

library(plyr)
library(ggplot2)
x <- seq(0, 4, length.out=100)
alpha <- 1:5
data <- mdply(alpha, function(a, x) data.frame(v=a*x^a, x=x), x)

p <- ggplot(data, aes(x=x, y=v, color=X1)) +
  geom_line() + 
  ylab(TeX('$\\alpha  x^\\alpha$, where $\\alpha \\in 1\\ldots 5$')) +
  ggtitle(TeX('Using $\\LaTeX$ for plotting in ggplot2. $\\newline$ I $\\heartsuit$ ggplot!')) +
  coord_cartesian(ylim=c(-1, 10)) +
  guides(color=guide_legend(title=NULL)) +
  scale_color_discrete(labels=lapply(sprintf('$\\alpha = %d$', alpha), TeX)) 

print(p)

image

\newline support

Thanks for the great package it has helped me immensely. One thing I quite haven’t figured out is how to add a \newline or \n in a plot. I frequently have long facet labels and/or legend labels that need both line breaks and superscripting. I noticed in issue #8 and #10 it is suggested to use \n to break the line but this does not appear to actually work as suggested.

CRAN release?

The current dev version is superior to the current CRAN version.
Any plans for a CRAN release?

error when using `;`

Hello,

For a publication I'd like to add the following notation in ylab:

Screenshot 2022-01-23 at 20 42 48

I have thus tried:

plot(x = rnorm(10),
     y = rnorm(10),
     ylab = TeX(r'($\bar{A}^{a;a \rightarrow i}_{x;n\rceil}$)'))

which gives the error:

Screenshot 2022-01-23 at 20 44 27

It seems to come from ; because this code works fine:

plot(x = rnorm(10),
     y = rnorm(10),
     ylab = TeX(r'($\bar{A}^{a,a \rightarrow i}_{x,n\rceil}$)'))

Screenshot 2022-01-23 at 20 45 52

Any idea how I could fix it?

I use version 0.9.0 of latex2exp, and here is my session info:

> sessionInfo()
R version 4.1.1 (2021-08-10)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Monterey 12.1

Matrix products: default
LAPACK: /Library/Frameworks/R.framework/Versions/4.1/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] latex2exp_0.9.0 tidyr_1.1.4    

loaded via a namespace (and not attached):
 [1] pillar_1.6.4      compiler_4.1.1    prettyunits_1.1.1 remotes_2.4.2     tools_4.1.1      
 [6] testthat_3.1.1    pkgbuild_1.3.1    pkgload_1.2.4     memoise_2.0.1     lifecycle_1.0.1  
[11] tibble_3.1.6      pkgconfig_2.0.3   rlang_0.4.12      DBI_1.1.2         cli_3.1.0        
[16] curl_4.3.2        fastmap_1.1.0     withr_2.4.3       dplyr_1.0.7       stringr_1.4.0    
[21] generics_0.1.1    desc_1.4.0        fs_1.5.2          vctrs_0.3.8       devtools_2.4.3   
[26] rprojroot_2.0.2   tidyselect_1.1.1  glue_1.6.0        R6_2.5.1          processx_3.5.2   
[31] fansi_0.5.0       sessioninfo_1.2.2 purrr_0.3.4       callr_3.7.0       magrittr_2.0.1   
[36] usethis_2.1.5     ps_1.6.0          ellipsis_0.3.2    assertthat_0.2.1  utf8_1.2.2       
[41] stringi_1.7.6     cachem_1.0.6      crayon_1.4.2     
Warning messages:
1: In doTryCatch(return(expr), name, parentenv, handler) :
  display list redraw incomplete
2: In doTryCatch(return(expr), name, parentenv, handler) :
  invalid graphics state
3: In doTryCatch(return(expr), name, parentenv, handler) :
  invalid graphics state

Thanks in advance!

Cannot handle \alpha_{02}

Describe the bug
Please briefly describe your problem and what output you expect.

I tried to print $ \alpha_{02} $ but it only can print $ \alpha_2 $ and omits 0.
To Reproduce

  1. Paste the output of sessionInfo() (this should show, at minimum, the version of R, the platform, and the architecture you are running on)

R version 4.1.1 (2021-08-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19044)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252 LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C LC_TIME=English_United States.1252

attached base packages:
[1] stats graphics grDevices utils datasets methods base

other attached packages:
[1] latex2exp_0.9.6 ggplot2_3.3.6

loaded via a namespace (and not attached):
[1] rstudioapi_0.13 magrittr_2.0.1 tidyselect_1.1.1 munsell_0.5.0 colorspace_2.0-2 R6_2.5.1 rlang_1.0.6
[8] fansi_0.5.0 stringr_1.4.0 dplyr_1.0.10 tools_4.1.1 grid_4.1.1 gtable_0.3.0 utf8_1.2.2
[15] cli_3.4.1 DBI_1.1.2 withr_2.4.3 digest_0.6.28 assertthat_0.2.1 tibble_3.1.8 lifecycle_1.0.3
[22] farver_2.1.0 purrr_0.3.4 vctrs_0.5.1 glue_1.6.2 labeling_0.4.2 stringi_1.7.5 compiler_4.1.1
[29] pillar_1.8.1 generics_0.1.1 scales_1.1.1 OncoPh1BLRM_1.4.5 pkgconfig_2.0.3

  1. Include a short snippet of code I can use to reproduce the problem. You can use reprex::reprex() to quickly prepare a reproducible example.

a <- 1:100
plot(a, a^2, xlab=TeX("$\alpha$"), ylab=TeX("$\alpha^{02}$"))

  1. What environment are plotting from? (e.g. RStudio, the R Console, Visual Studio Code, etc.)

R Studio

  1. If the bug comprises unexpected visual output from TeX(), please paste a screenshot of what you see on your system. You can plot a single TeX expression by running
# example
library(latex2exp)
plot(TeX(r"($\alpha + \beta$)")) # <-- this doesn't render correctly

Expected behavior
A clear and concise description of what you expected to happen.

Additional context
Add any other context about the problem here.

Render issues of parentheses \left[, ...

Hi,
when I use for example

plot(TeX("Day time $\ \\left[ hours \\right] $"), cex=2, main="")

R does not display the brackets.
It looks like this:
image

When I use this instead:
plot(TeX("Day time $\ \\lbrack hours \\rbrack $"), cex=2, main="")

it renders properly.

image

Using vector values

Is it possible to vector values (using R objects) within the TeX expression?

Example (It did not work; I had to include the values manually in the TeX code):

p_1 <- .2
ntrials <- 10
success <- 0:ntrials
exp_v_1 <- ntrials*p_1
var_v_1 <- ntrials*p_1*(1-p_1)

plot(success, dbinom(success, size=10, prob=p_1),type='h',
     main = TeX(r'($p = `r p_1`; E(X)=`r exp_v_1`;Var(X)=`r var_v_1`$)', italic = T),
     ylim = c(0,.3),
     xlab=substitute(italic(X)), ylab=substitute(italic(f(X))), frame.plot = F, col="blue")
text(x = 0, y= .3, "a)")

Desired behavior resulting in:

image

Square brakets apparently need to be escaped

Hi,

thanks for this very useful package!

I notice that apparently square brakets need to be escaped to prevent being ignored, together with whatever is enclosed.

plot(TeX(r"($a [b]$)"))

just shows "a", while

plot(TeX(r"($a \[b\]$)"))

shows "a[b]"

It would be nicer that square brakets be treated as in LaTeX without a dedicated escaping.

Greetings!

Alberto

Error in using TeX inside geom_text()

I would like to annotate math formulas on the plot using geom_text() and I specified the TeX expression to the label argument in following code.

library(ggplot2)
library(latex2exp)

p <- ggplot(mtcars, aes(mpg, cyl)) + 
  geom_point() + 
  geom_text(aes(x = 30, y = 7, label = TeX("$\\theta$ = 270")))
print(p)

However, it produces following error

Don't know how to automatically pick scale for object of type expression. Defaulting to continuous.
Error in as.data.frame.default(x[[i]], optional = TRUE) : 
  cannot coerce class ‘"expression"’ to a data.frame

Rendering mathematical operators and symbols in ggplot and plot

I seem to be having troubles displaying mathematical operators and other symbols while using ggplot() and plot() in RStudio. I reinstalled and deleted all R and RStudio folders. I tried opening the graphs in maximized new window. I haven't changed much in settings, only Appearance to Vibrant Ink and Sweave PDF Preview after compile using to RStudio Viewer. Otherwise, all of my RStudios settings should be set to default.
Unicode characters work correctly.

> sessionInfo()
R version 4.2.2 (2022-10-31 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 22621) # Incorrect, Windows 11 Home, 22H2, build 22621.1344

Matrix products: default

locale:
[1] LC_COLLATE=Czech_Czechia.utf8  LC_CTYPE=Czech_Czechia.utf8    LC_MONETARY=Czech_Czechia.utf8 LC_NUMERIC=C                   LC_TIME=Czech_Czechia.utf8    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] ggplot2_3.4.1   latex2exp_0.9.6

loaded via a namespace (and not attached):
 [1] zip_2.2.2        Rcpp_1.0.10      compiler_4.2.2   pillar_1.8.1     tools_4.2.2      digest_0.6.31    evaluate_0.20    lifecycle_1.0.3  tibble_3.2.0    
[10] gtable_0.3.1     pkgconfig_2.0.3  rlang_1.0.6      openxlsx_4.2.5.2 cli_3.6.0        rstudioapi_0.14  yaml_2.3.7       xfun_0.37        fastmap_1.1.1   
[19] withr_2.5.0      stringr_1.5.0    dplyr_1.1.0      knitr_1.42       generics_0.1.3   vctrs_0.5.2      grid_4.2.2       tidyselect_1.2.0 glue_1.6.2      
[28] R6_2.5.1         fansi_1.0.4      rmarkdown_2.20   farver_2.1.1     magrittr_2.0.3   scales_1.2.1     htmltools_0.5.4  colorspace_2.1-0 labeling_0.4.2  
[37] utf8_1.2.3       stringi_1.7.12   munsell_0.5.0   
library(latex2exp)
library(ggplot2)

ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  xlab(TeX(r"($\alpha \cdot \beta$)")) + # incorrect for \cdot, works for alpha and beta
  ylab(TeX(r"($\pm \neg \subset$)")) + # incorrect
  labs(title = "\u03b1 \u2022 \u03b2") # correct

plot(TeX(r"($\alpha \cdot \beta$)")) # \cdot wrong again

image
image

Add ceil and floor symbols

Hello,

Unless I'm mistaken, \lceil, \rceil, \lfloor and \rfloor symbols are not supported (see section "Supported LaTeX" in this vignette).

I would like to use the \rceil symbol in the axis label of my plot, would you mind adding these symbols?

Thanks in advance for your help and for building this package.

Regards,
Antoine

Error when rendering math outside of math mode

This throws an error:

> TeX(r"(\alpha+\beta)")
Error in TeX("\\alpha+\\beta") : 
  Error while converting LaTeX into valid plotmath.
Original string: \alpha+\beta
Parsed expression: alpha+*beta
Error in str2expression(rendered) : <text>:1:7: unexpected '*'
1: alpha+*

while this doesn't:

> TeX(r"($\alpha+\beta$)")
   LaTeX: $\alpha+\beta$ 
plotmath: alpha + beta 

They should be equivalent.

ggplot axis tick labels

I'm running into a problem when trying to use the script to label the tick marks using ggplot. There is no error or warning message and the code runs fine, but it leaves the labels blank. Using your example from ggplot graphics, I've edited it to show the problem.

library(plyr)
x <- seq(0, 4, length.out=100)
alpha <- 1:5
data <- mdply(alpha, function(a, x) data.frame(v=a*x^a, x=x), x)

p <- ggplot(data, aes(x=x, y=v, color=X1)) +
geom_line() +
coord_cartesian(ylim=c(-1, 10)) +
guides(color=guide_legend(title=NULL)) +
scale_color_discrete(labels=lapply(c("\alpha", "\beta", "\gamma", "\delta", "\epsilon"), latex2exp)) +
scale_x_continuous(labels=lapply(c("\alpha", "\beta", "\gamma", "\delta", "\epsilon"), latex2exp))

print(p)

image

Operator '\otimes' won't display

Hello,

Some operators such as \times and \otimes wil only display a white square. I am using version 4.2.1 of R.

library(latex2exp)
plot(TeX(r"($Z \otimes D_{jk}$)")) # displays white square instead of \otimes, see picture

image

itliac for the entire expression?

Dear Stefano,

I had an issue when using Tex to create an expression which only requires variables to be italic.

For instance, latex2exp::TeX("$a$ is a variable", italic = TRUE) would return all characters, including "is a variable", as italic.

My tricky solution is by using

latex2exp::TeX("$a$ is a variable", output = "character") %>% 
    gsub("'a'", "italic(a)", .) %>% 
    parse(text = .)

Is there any better solution to make only $a$ italic?

Regards,
Shun

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.