Here's an example of a problem:
example=data.frame(x1=c(1,4.1,7),x2=c(4,7.1,10),
y1=c(1,1,5),y2=c(2,2,6),text=c('Example','A Bigger Example','little.lite'))
example$xmid = (example$x1+example$x2)/2
example$ymid = (example$y1+example$y2)/2
ggplot()+geom_rect(data=example,aes(xmin=x1,xmax=x2,ymin=y1,ymax=y2,fill=text))+
geom_text(data=example,aes(x=xmid,y=ymid,label=text))
The output looks like this:
I've tried adjusting the size of labels by using the number of characters in the string, but it doesn't take into account spacing and kerning of different characters in non-monospace fonts. For example,
example$text_size=24/nchar(as.character(example$text))
ggplot()+geom_rect(data=example,aes(xmin=x1,xmax=x2,ymin=y1,ymax=y2,fill=text))+
geom_text(data=example,aes(x=xmid,y=ymid,label=text,size=text_size))+
scale_size_continuous(range=c(4,8))
The output then looks like this:
While the widths of the text in the lower boxes are the same, the text width of the string with many l's and t's is smaller. Is there any way to calculate the spacing in advance so that the width of all of the different characters into account?