How to adjust plotmath in ggplot2 annotate()

It seems that hjust and vjust options in annotate() do not work if the text label includes plotmath expressions. Below is the sample code.

library(tidyverse)
library(ggplot2)

test_data = tibble(x=1:100,y=100:1)

ggplot(test_data, mapping=aes(x=x, y=y)) + 
  geom_point() +
  annotate(geom = "text", 
           x = 100, y = 100, 
           hjust = 1, vjust = 1, 
           label = expression(atop(1+1==2, 
                                   italic("hjust does not work correctly"))))

Below is the output of the sample code.
image
What I want is to locate each line of the label to the rightmost position of the plot. Is there any way to do this?

I think this is because you are using atop: hjust and vjust won't control how the top and bottom text will be place above on another in the plotmath atop display.

I would do it in two calls to annotate, changing the y to get the position right (i may have put a big one here but you can control easily)

library(tidyverse)
library(ggplot2)

test_data = tibble(x=1:100,y=100:1)

ggplot(test_data, mapping=aes(x=x, y=y)) + 
  geom_point() +
  annotate(geom = "text", 
           x = 100, y = 100, 
           hjust = 1, vjust = 1, 
           label = '1+1==2') +
  annotate(geom = "text", 
           x = 100, y = 90, 
           hjust = 1, vjust = 1, 
           label = 'italic("hjust does not work correctly")', 
           parse = TRUE)

Created on 2020-05-12 by the reprex package (v0.3.0)

Hope it helps

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.