Search code examples
rggplot2annotationsgeom-text

how to give a data two annotations using ggplot2 in R


Here is my example:

a <- data.frame(X=c(1,2,3,4,5),Y=c(1,2,3,4,5),A1=c(1,2,3,4,5),A2=c(6,7,8,9,10))

A1 and A2 are two types of annotation. Now I only can add one annotation into the plot.

library(ggplot2)
ggplot(data=a,aes(x=X,y=Y,label=A1)) +
      geom_point() +
      geom_text(hjust=0,vjust=-1)

Can I put A1 and A2 into the plot? So it looks like A1 and A2 are one the same vertical line, and A1 is on top of A2?


Solution

  • You can use different geom_text:

    library(ggplot2)
    ggplot(a,aes(X, Y)) +
          geom_point() +
          geom_text(aes(label = A1), ahjust = 0, vjust = -2.5) +
          geom_text(aes(label = A2), ahjust = 0, vjust = -1) +
          ylim(c(min(a$Y), max(a$Y) + 1))
    

    enter image description here