ohnoplus
ohnoplus

Reputation: 1335

Using the "*" or "|" symbol in ggplot2 annotate

I want to put the following equation into a ggplot in R using the annotate() function.

equation

The closest I seem to be able to get so far is the following

ggplot()+ annotate("label", x = 1, y = 1, label = "APC == 0.50 ~ Depth ^ {-0.99} * (Cone == 0~Net == 1) ^ {0.59}", parse = TRUE, size = 5)

ok annotation

Which is fine, but it would be nice to be able to add the * and | symbols from the equation. I tried the following:

ggplot()+ annotate("label", x = 1, y = 1, label = "APC == 0.50 * Depth ^ {-0.99} * (Cone == 0|Net == 1) ^ {0.59}", parse = TRUE, size = 5)

but it just ends up looking weird

strange looking annotation

Any advice about how I can get the or and star symbols added?

Also imaginary bonus points if somebody can explain to me what actually is happening with the | symbol when I try to use it, why does it appear where it does and add parentheses and a comma?

Upvotes: 4

Views: 1171

Answers (1)

Maurits Evers
Maurits Evers

Reputation: 50718

An alternative might be to use LaTeX expressions through latex2exp::TeX

library(ggplot2)
library(latex2exp)
ggplot() +
    annotate(
        "label",
        x = 1, y = 1,
        label = TeX("$APC = 0.50 \\times Depth^{-0.99} \\times (Cone = 0 | Net = 1)^{0.59}$"),
        size = 5)

enter image description here

Two additional comments:

  1. It is perhaps important to point out that latex2exp supports some LaTeX expressions but not all. For example, in LaTeX \vert and | are synonymous, but while latex2exp correctly typesets | it fails for \vert. The latex2exp vignette has a section "Supported LaTeX" that contains a list of supported LaTeX expressions.
  2. All LaTeX commands in latex2exp::TeX need to be prefixed (escaped) with an additional backslash. So \times becomes \\times.

Upvotes: 6

Related Questions