Position ggplot text in each corner

后端 未结 2 2034
迷失自我
迷失自我 2020-12-31 03:16

I\'ve got a scatter plot with a horizontal and a vertical line, which depict thresholds values, and therefore they divide the plot into four quadrants. I\'d like to label th

相关标签:
2条回答
  • 2020-12-31 03:32

    This example uses the Inf & -Inf values to position the text at the corners and then hjust and vjust arguments in the geom_text to position the text inside the plot. Use the hjustvar and vjustvar to position them further into or outside the plot.

    As mentioned by @baptiste it's best to use a new data set for the annotations

    df <- data.frame(x2=rnorm(100),y2=rnorm(100));library(ggplot2)
    
    annotations <- data.frame(
            xpos = c(-Inf,-Inf,Inf,Inf),
            ypos =  c(-Inf, Inf,-Inf,Inf),
            annotateText = c("Bottom Left (h0,v0)","Top Left (h0,v1)"
                            ,"Bottom Right h1,v0","Top Right h1,v1"),
            hjustvar = c(0,0,1,1) ,
            vjustvar = c(0,1,0,1)) #<- adjust
    
    
      ggplot(df, aes(x2, y2)) + geom_point()+
                geom_text(data=annotations,aes(x=xpos,y=ypos,hjust=hjustvar,vjust=vjustvar,label=annotateText))
    

    If we wanted to change any of the text positions, we would adjust the horizontal positions with hjustvar and the vertical positions with vjustvar.

    # How To Adjust positions (away from corners)
    annotations$hjustvar<-c(0,  -1.5,  1,  2.5)  # higher values = right, lower values = left 
    annotations$vjustvar<-c(0,1,0,1) # higher values = up, lower values = down 
    
    ggplot(df, aes(x2, y2)) + geom_point()+
            geom_text(data = annotations, aes(x=xpos,y=ypos,hjust=hjustvar,
                                              vjust=vjustvar,label=annotateText))
    

    Hope this works!

    0 讨论(0)
  • 2020-12-31 03:43

    when adding annotations, make sure to give a new data set, or to use annotate, otherwise multiple labels will be superimposed giving a jagged look. Here's a minimal change from the other answer,

    df <- data.frame(x2=rnorm(100),y2=rnorm(100))
    library(ggplot2)
    
    annotations <- data.frame(
       xpos = c(-Inf,-Inf,Inf,Inf),
       ypos =  c(-Inf, Inf,-Inf,Inf),
       annotateText = c("Text","tExt","teXt","texT"),
       hjustvar = c(0,0,1,1) ,
       vjustvar = c(0,1.0,0,1))
    
    
      ggplot(df, aes(x2, y2)) + geom_point()+
      geom_text(data = annotations, aes(x=xpos,y=ypos,hjust=hjustvar,
                    vjust=vjustvar,label=annotateText))
    

    0 讨论(0)
提交回复
热议问题