Search code examples
rggplot2plotgeom-text

How to vary the length of text in geom_text in R ggplot?


I'm plotting some text using geom_label in ggplot in R but I can't figure out how to vary the size of text based on a variable. Note that by "size" I do not mean the width of the text but its length. Consider the following dummy data and the figure it generates:

x.cord <- c(4,5,1,6)
duration <- c(0.4, 0.7, 0.2, 0.3)
text <- c("know", "boy", "man", "gift")

df <- data.frame(cbind(x.cord, duration, text))


p <- ggplot(df, aes(x.cord, rownames(df), label = text))

p + geom_label(aes(fill=text))

enter image description here

In the above plot, I am able to plot the text positioned at the x.cord (i.e. x-coordinate), but I also want the length of the text to be equal to the duration variable.

If I use the size parameter as follows:

p + geom_label(aes(fill=text, size=duration))

I get the following figure: enter image description here

I'm able to control the 'width' of the text based on the duration variable as seen in the above figure but I can't seem to find any parameter which would help me control the 'length' of the text box. Any suggestions how can I do that?


Solution

  • Not the most elegant solution, but I am not 100% sure what you are after. I think this is also kind of what EcologyTom had in mind. Maybe something like this?

    x.cord <- c(4,5,1,6)
    duration <- c(0.4, 0.7, 0.2, 0.3)
    text <- c("know", "boy", "man", "gift")
    df <- data.frame(cbind(as.numeric(x.cord), as.numeric(duration), text))
    
    p = ggplot(df, aes(x.cord, as.numeric(rownames(df)), label = text)) +
      geom_tile(aes(x = x.cord, y = as.numeric(rownames(df)), width = duration, height = 0.1, fill = text)) +
      geom_text()
    p
    

    enter image description here