2

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?

Lukas D. Sauer
  • 355
  • 2
  • 11

2 Answers2

2

Your label should be placed outside of aes().

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

enter image description here

benson23
  • 16,369
  • 9
  • 19
  • 38
  • Thank you very much. Is there a possibility to adapt this so that it works with variables as well. Let's say I replace the 1 in the example with `a` and initialize `a=3` earlier on. Is there a way to obtaIn `3/2=1.5` and not `a/2=a/2`? – Lukas D. Sauer Jan 31 '22 at 10:35
2

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

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
  • This answer is easily adaptable to the case where I want to replace numbers by variables. Thank you! `a = 3; ggplot(data=NULL) + geom_point(aes(x=0.5, y=0)) + geom_text(aes(x=0.5, y=-0.1), label = paste("frac(",a,",2) ==", a/2), parse=TRUE) + xlim(-1,1) + ylim(-1, 1)` – Lukas D. Sauer Jan 31 '22 at 11:28