What is a good way to fit text inside a plotting a

2019-07-04 11:56发布

问题:

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?

回答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:



标签: r text ggplot2