Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add text annotations at consistent locations in facet_grid when scale = 'free_y' + ggplot2 + r

I need to annotate a set of chats in a facet grid where the y axis is scale is set to scale = 'free_y'.

As the scales are very different, when I set the y position of the geom_text the text location is also very different for each graph. Is there any method to correct for this so that they are all in the same elate x,y position on each chart in the facet grid?

The example below demonstrates the problem:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

library(ggplot2)

df <- data.frame(name = c('Jim',"Bob", "Sue",'Jim',"Bob", "Sue",'Jim',"Bob", "Sue"), 
                 r = c(1,10,100,2,20,200,3,30,300), z = c(1,10,100,2,20,200,3,30,300))
  
p <- ggplot(df, aes(z, r)) + geom_line()

p <- p + facet_grid(vars(name),scales = "free")

dfl <- data.frame(name = c('Jim',"Bob", "Sue"), r = c(-0.2, 0.5, -0.4))

p + geom_text(data = dfl, aes(200, 10,label = r), check_overlap = T)

enter image description here

Ideally, in this example, the labels would all be the same position as the first chart in the facet gris "Bob".

I have reviewed this previous question, which addresses text annotation on a single chart in a facet grid, but not the placement in the case of different y scales per facet – Annotating text on individual facet in ggplot2

>Solution :

Here is how you can control the annotations:

p + geom_text(
  size    = 5,
  data    = dat_text,
  mapping = aes(x = Inf, y = Inf, label = label),
  hjust   = 1.05,
  vjust   = 1.5
)

dat_text <- data.frame(
  label = c(-0.2, 0.5, -0.4),
  name  = c('Jim', 'Bob', 'Sue')
)

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading