1

I am trying to figure out how to make the text size of a text variable based on its length. I don't know how to explain it better :D

I have a text field where a user can enter text. I want the text to always be the "maximum possible" size in a certain text box, but never go beyond the edge of the text box. So an automatic scaling down of the text size should happen as soon as a text has a certain length.

The borders of the text box are not defined in R, but via the "background" - a bit difficult to explain. I have a background, so to speak, on which I want to draw the text, which defines certain boundaries.

I had thought about simply predefining sizes for certain "quantity bands", according to the motto "If input between X and Y characters, then use size Z". However, I wanted to ask if you know of a cleaner solution.

Thank you and best regards

My Code:

Gruppenname <- "ExampleName"

Ausgabe <- ggdraw() +
draw_text(Gruppenname, x = 0.1, y = 0.385, color="#9ad3b8", size=140, family = "Oswald", hjust = 0,vjust = 0)

Current Ouput: enter image description here

Goal:

enter image description here

LePyka
  • 181
  • 8

2 Answers2

1

Package ggfittext provides a function to do precisely that:

library(cowplot)
library(ggfittext)
library(ggplot2)

Gruppenname <- "ExampleName"

x.low <- 0.1
x.high <- 0.8
y.low <- 0.385
y.high <- 0.8

Ausgabe <- ggdraw() +
  geom_rect(aes(xmin=x.low,ymin=y.low,xmax=x.high,ymax=y.high)) +
  geom_fit_text(aes(xmin=x.low,ymin=y.low,
                    xmax=x.high,ymax=y.high,label=Gruppenname),
                place="bottomleft",grow=T)

Ausgabe

enter image description here

Gruppenname <- "LongerExampleName"

Ausgabe <- ggdraw() +
  geom_rect(aes(xmin=x.low,ymin=y.low,xmax=x.high,ymax=y.high)) +
  geom_fit_text(aes(xmin=x.low,ymin=y.low,xmax=x.high,ymax=y.high,label=Gruppenname),place="bottomleft",grow=T)

Ausgabe

enter image description here

Julian_Hn
  • 2,086
  • 1
  • 8
  • 18
0

What input or variable governs the size? In my solution, i just made a function that multiples x to the size argument.

Gruppenname <- "ExampleName"

drawit <-  function(x){ggdraw()+draw_text(Gruppenname, 
                  x = 0.1, y = 0.385, color="#9ad3b8", 
                  size=222*x, 
                  family = "Oswald", hjust = 0,vjust = 0)}

drawit(.6)
Ben
  • 1,113
  • 10
  • 26