2

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?

Siddharth Vashishtha
  • 1,090
  • 2
  • 9
  • 15

1 Answers1

4

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

Mojoesque
  • 1,166
  • 8
  • 15
  • That works! Although I noticed that geom_tile is sometimes below the text, sometimes above the text or sometimes enclosed with the text as in your figure. Is there a way that I can ensure it is always below the text? – Siddharth Vashishtha Nov 23 '18 at 10:19
  • I don't think I understand. It is always below the text because we created the geom first. Or do you mean the purple one which is shorter than the text? If that is an issue you have to reduce the text size since the size of the bars is fixed in your example. – Mojoesque Nov 23 '18 at 10:23
  • Yep, this is the sort of thing I had in mind. I think it should also be possible to make the bars extend from `xcord` to `xcord + duration`, if you wanted them to stretch to the right, rather than just overlap the `xcord` point – EcologyTom Nov 23 '18 at 10:46
  • Yeah, for more direct control one should use `geom_rect()` instead of `geom_tile()`. It takes x.min, x.max, y.min, y.max, instead of a mid-point and width/height. So it's better for full control, but harder to properly align it with the text. – Mojoesque Nov 23 '18 at 11:11