Home > Enterprise >  Fix the vertical position of `geom_label` in ggplot
Fix the vertical position of `geom_label` in ggplot

Time:04-20

Let say I have below ggplot

library(ggplot2)
set.seed(1)
df = data.frame(x = rnorm(100, 0, 1), y1 = rnorm(100, 10, 1), y2 = rnorm(100, 50, 1))

ggplot(df)  
geom_point(aes(x = x, y = y1))   
geom_label(aes(x = mean(range(df$x)), y = 10), label = 'Plot with y', label.padding = unit(.7, 'lines'), fill = '#000000', color = '#ffffff', alpha = 0.2)

enter image description here

Now with second variable y2, I have below ggplot

ggplot(df)  
geom_point(aes(x = x, y = y2))   
geom_label(aes(x = mean(range(df$x)), y = 10), label = 'Plot with y', label.padding = unit(.7, 'lines'), fill = '#000000', color = '#ffffff', alpha = 0.2)

enter image description here

I would like to fix the relative vertical position of the geom_label in these two plots, which should be 100 pixels/points below from the top boundary of my plot area, irrespective of the range on y axis.

Is there any option available with geom_label to perform the same?

Any pointer will be very helpful

CodePudding user response:

One option would be to add your labels as grobs via annotation_custom which allows to position your labels using relative coordinates of the plot area. For convenience I use gridtext::richtext_grob to create the label grob.

library(ggplot2)
library(gridtext)

set.seed(1)
df = data.frame(x = rnorm(100, 0, 1), y1 = rnorm(100, 10, 1), y2 = rnorm(100, 50, 1))

label_grob <- gridtext::richtext_grob(
  text = 'Plot with y',
  x = unit(0.5, "npc"),
  y = unit(1, "npc") - unit(100, "pt"),
  padding = unit(.7, "lines"),
  r = unit(0.15, "lines"),
  gp = grid::gpar(col = '#ffffff'),
  box_gp = grid::gpar(col = '#000000', fill = '#000000', size = 0.25)
)

ggplot(df)  
  geom_point(aes(x = x, y = y1))   
  annotation_custom(grob = label_grob)

ggplot(df)  
  geom_point(aes(x = x, y = y2))    
  annotation_custom(grob = label_grob)

  • Related