rggplot2geom-textmathematical-typesetting

ggplot geom_text is messing up text order when using R mathematical notation


I am trying to label points in ggplot using geom_text. I would like to use R mathematical notation for the labelling. For example, a point at the x-coordinate 0.5 should have the label 1/2=0.5, where 1/2 is written as a fraction. I have been trying this code:

ggplot(data=NULL) +
  geom_point(aes(x=0.5, y=0)) +
  geom_text(aes(x=0.5, y=-0.1,
                label = paste("frac(1,2)"," = ", 1/2)), parse=TRUE) +
  xlim(-1,1) +
  ylim(-1, 1)

However, the order of the label is messed up, as the picture below shows:

Messy order of the label text

Instead of 1/2=0.5, I receive =(1/2,0.5). How can I obtain the correct order when using frac() in my label text?


Solution

  • Place label outside aes and use double ==, like it is said in help("plotmath").

    ggplot(data=NULL) +
      geom_point(aes(x=0.5, y=0)) +
      geom_text(aes(x=0.5, y=-0.1),
                label = paste("frac(1, 2) == ", 1/2), parse=TRUE) +
      xlim(-1,1) +
      ylim(-1, 1)
    

    enter image description here