Search code examples
rggplot2geom-textright-align

ggplot - Keep a variable length text inside canvas


I need that the text showed by geom_text must be inside the canvas of the plot. The problem is that the content of the geom_text is dynamically assigned. So, my question is, how can I make the below plot in which the content of the variable named variableLabelSize is fully showed inside the canvas.

My first thought was to create a function in which variableLabelSize is parameter of xLegPos. Second, I also tried to use the hjust='inward' but I think it may only work with data mapped to aes. Any ideas are welcome : )

I'm running this demo:

require(ggplot2)
variableLabelSize = "Variable length size text"
xLegPos = 100 - 15

df1 = data.frame(x=1:100, y=rnorm(100))
p = ggplot(df1, aes(x=x, y=y)) + geom_point()
p = p + geom_hline(yintercept = 2)
p = p + geom_text(x=xLegPos, y=2, label=variableLabelSize)
p

enter image description here

I think it's important to point out that my problem is different from question How to make geom_text plot within the canvas's bounds because in my example, the geom_text is not binded to a dataframe. I mean, I do not use geom_text(aes(...)), I use geom_text().


Solution

  • I ended up finding a quite simple way of doing that using the parameter hjust=1.

    Also, I kept the x value for geom_text with its maximum value, that is, max(df1$x).

    Below, I'm plotting three texts in which all of them are aligned to the right:

    require(ggplot2)
    df1 = data.frame(x=1:100, y=rnorm(100))
    p = ggplot(df1, aes(x=x, y=y)) + geom_point()
    p = p + geom_hline(yintercept = c(-3, -2, 2))
    
    variableLabelSize = "Variable length size text"
    p = p + geom_text(x=max(df1$x), y=2, label=variableLabelSize, hjust=1) # added hjust=1
    variableLabelSize = "Short text"
    p = p + geom_text(x=max(df1$x), y=-3, label=variableLabelSize, hjust=1) # added hjust=1
    variableLabelSize = "Very very very very very very long text"
    p = p + geom_text(x=max(df1$x), y=-2, label=variableLabelSize, hjust=1) # added hjust=1
    
    p
    

    enter image description here