3

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:

enter image description here

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:

enter image description here

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?

Max Candocia
  • 4,294
  • 35
  • 58

1 Answers1

1

Per suggestion by @Tyler Rinker, I used the strwidth function instead of nchar.

example$text_size2=24/strwidth(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_size2))+
scale_size_continuous(range=c(4,8))

The end result looks like this:

enter image description here

Max Candocia
  • 4,294
  • 35
  • 58
  • When I try to run your example, I get `Error in strwidth(as.character(example$text)) : plot.new has not been called yet`. From the documentation, one can see that the function extracts the width from the graphics device if `units = "user"` (default these days) and seems not to work with ggplot2. Use `units = "figure"` to make the routine work in 2018 versions of R and ggplot2. – Mikko Jun 15 '18 at 07:23