Can ggfittext automatically choose rotation for text?

0

Issue

I have a plot with labelled rectangles. To ensure text stays inside the rectangle I’m using the ggfittext package. Example below:

library(ggplot2)
library(ggfittext)

df <- data.frame(
  xmin = c(1000, 4000), xmax = c(3000, 5000),
  ymin = c(1, 3), ymax = c(2, 5),
  label = "My Label"
)

p <- ggplot(df, aes(xmin = xmin, xmax = xmax,
                    ymin = ymin, ymax = ymax)) +
  geom_rect(fill = "grey60")
p + geom_fit_text(aes(label = label),
                  size = 40)

As one might notice, the label in the second rectangle on the right would fit better if it were rotated, and the label wouldn’t need to be shrunk as much. I can easily do that manually:

p + geom_fit_text(aes(label = label),
                  size = 40, angle = c(0, 90))

Created on 2021-09-29 by the reprex package (v2.0.1)

However, I’d like to automatically detect if text placement is better horizontally or vertically. Is there an option to do this in ggfittext or alternative packages? I’m searching for an answer where the visual dimensions are more important than the data dimensions: these rectangles in the example are much wider than they are tall in data-space, but not in visual-space.

Solution

I’m the author of ggfittext. ggfittext can’t automatically rotate the text in the way you’re describing, and I’m not aware of any package that will do this.

geom_fit_text() does include a reflow argument that will reflow multi-word text to better fit the box. This doesn’t work by simply shortening the line length until the text fits, but will find the line length that makes the aspect ratio of the text closest to that of the box. Obviously this is more useful with longer text labels.

library(ggplot2)
library(ggfittext)

df <- data.frame(
  xmin = c(1000, 4000), xmax = c(3000, 5000),
  ymin = c(1, 3), ymax = c(2, 5),
  label = "My Label"
)

ggplot(df, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax)) +
  geom_rect(fill = "grey60") +
  geom_fit_text(aes(label = label), size = 40, reflow = TRUE)

Created on 2021-12-18 by the reprex package (v2.0.1.9000)

Answered By – wilkox

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More