Search code examples
rggplot2label

Removing lines spaces in a ggplot2 label within a graph


Does anyone know how to remove the space between the lines of a label in the geom_text label function in ggplot? Below is the code I have but introduces a huge gap among the lines, see in the image.linear regression output with p and R² with a big space `

s + geom_text(aes(x=45, y=0.8, size=19,
                  label= "R²= 0.1\np = 0.17"))

`

I do not know what I could do. Have already searched online and the only resources are related to axis labels


Solution

  • The default lineheight aesthetic is 1.2. Set it to a smaller value to decrease the spacing between lines of text.

    library(ggplot2)
    
    ggplot() +
      geom_text(aes(x = 45, y = 0.8, size = 19, label = "R²= 0.1\np = 0.17"),
                lineheight = 0.5)
    

    Created on 2022-11-04 by the reprex package (v2.0.0)

    (Additionally, you might want to set the font size outside the aes() function if you only have a single font size)