What is a good way to fit text inside the plotting area with ggplot2 using a predetermined width for the text?

Here is 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 result is as follows:

enter image description here

I tried to adjust the size of the labels using the number of characters per line, but did not take into account the spacing and kerning of different characters in non-monospaced fonts. For instance,

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 result is as follows:

enter image description here

While the width of the text in the lower boxes is the same, the width of the text of the line with many l and t is smaller. Is there a way to calculate the span in advance to take into account the width of all the different characters?

+2
source share
1 answer

Under the assumption of @Tyler Rinker, I used the strwidthfunction instead 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 is as follows:

enter image description here

0

Source: https://habr.com/ru/post/1598697/


All Articles