rggplot2annotate

Place (x,y) coordinate pairs in ggplot annotation label


I have a ggplot I'm using to illustrate some trig concepts via an RMarkdown document.

annotate("text",
             x = 0.97,
             y = 0.5,
             label = str_c("(~frac(sqrt(3),pi)", ",", "~frac(1,2))"),
             parse = TRUE,
             size = 3
             )

This fails with a complaint about the quoted comma. I am stumped. Every time I knit the document with that comma character in the label, it fails complaining of "unexpected ','".

Does anyone have a method to insert a literal comma in the label of a text annotation like this. Note: These annotations are one-offs and are not part of another data source.

I have tried:

label = str_c("(~frac(sqrt(3),pi)", ",", "~frac(1,2))")
label = str_c("(~frac(sqrt(3),pi)", "~,", "~frac(1,2))")
label = str_c("(~frac(sqrt(3),pi)", "&#2C", "~frac(1,2))")

label = "(~frac(sqrt(3),pi),~frac(1,2))"
label = "(~frac(sqrt(3),pi)~,~frac(1,2))"

All resulted in an error citing the literal comma character. If I remove that comma, I get the expected output, two values surrounded by parentheses, but separated by a blank space, not a comma.


Solution

  • A literal comma is a "special" character. Hence you have to put it in quotes. Additionally add a ~ or a * to make it a valid expression:

    library(ggplot2)
    
    ggplot() +
      annotate("text",
        x = 0.97,
        y = 0.5,
        label = paste0(
          "(~frac(sqrt(3),pi)",
          "~','",
          "~frac(1,2))"
        ),
        parse = TRUE,
        size = 8
      )