Search code examples
rggplot2geom-textannotate

Annotation label clipped in ggplot2


I'm trying to avoid the bottom annotation being clipped. It's the descender on the "p" that gets chopped off. I've used the "inward" option on vjust.

df <- data.frame(x=c(as.Date("2020-01-01"),as.Date("2022-01-01"))
                     ,y=c(0,1))
df
ggplot(df) +
  geom_point(mapping=aes(x=x,y=y)) +
  annotate("text",x=mean(df$x),y=-Inf,label="Clipped",hjust=0.5,vjust="inward",size=12,colour="red") +
  annotate("text",x=mean(df$x),y=Inf,label="Not Clipped",hjust=0.5,vjust="inward",size=12,colour="blue")

clipped text


Solution

  • A possible approach would be to use the min and max y values:

    library(tidyverse)
    
    df <- data.frame(
      x = c(as.Date("2020-01-01"), as.Date("2022-01-01")),
      y = c(0, 1)
    )
    
    ggplot(df) +
      geom_point(aes(x, y)) +
      annotate("text", x = mean(df$x), y = min(df$y), label = "Clipped", hjust = 0.5, vjust = "inward", size = 12, colour = "red") +
      annotate("text", x = mean(df$x), y = max(df$y), label = "Not Clipped", hjust = 0.5, vjust = "inward", size = 12, colour = "blue")
    

    Created on 2022-07-02 by the reprex package (v2.0.1)