wilkelab / ggtext

Improved text rendering support for ggplot2
https://wilkelab.org/ggtext/
GNU General Public License v2.0
655 stars 37 forks source link

Feature request: Justify text #94

Open SchmidtPaul opened 2 years ago

SchmidtPaul commented 2 years ago

[This issue is basically a copy of this stackoverflow post I created first to make sure I am not missing an obvious (alternative) solution.]

I would like to justify (not just align!) multiline text in my ggplots, i.e. mostly title, subtitle, caption and annotations via geom_text() etc.

Justified Text

To be clear, by "justified text" I mean adding space between words so that both edges of each line are aligned with both margins. The last line in the paragraph is aligned left. In the following image it would be the format on the right, highlighted in yellow:

enter image description here

reprex

Below is a reproducible example trying it with both {ggplot2} and {ggtext}. As you can see, I can only think of using hjust= (and halign= with {ggtext}) but they only align and do not justify multiline text.

library(ggtext)
library(tidyverse)

my_text <- "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
my_subtitle <- paste(rep(my_text, 5), collapse = " ")

df <- tibble(
  my_text = rep(my_text, 3),
  x = c(1, 2, 3),
  y = c(2, 1, 0),
  hjust = c(0, 0.5, 1),
  vjust = c(0, 0.5, 1)
)

ggplot() +
  ggtitle("ggtext::geom_richtext() with automatic word-wrapping") +
  ggtext::geom_textbox(
    data = df,
    width = unit(2, "inch"),
    box.color = NA,
    fill = NA,
    aes(
      label = my_text,
      x = vjust,
      y = hjust,
      hjust = hjust,
      vjust = vjust,
      halign = hjust,
      valign = vjust
    )
  ) +
  labs(subtitle = my_subtitle) +
  theme(plot.subtitle = ggtext::element_textbox_simple(hjust = 0, halign = 0))

Created on 2022-08-23 with reprex v2.0.2

SchmidtPaul commented 1 year ago

StackOverflow suggests interest in this: https://stackoverflow.com/questions/73384281/justify-multiline-text-in-ggplot2-title-subtitle-caption-geom-text-etc

Also, see this: https://twitter.com/nrennie35/status/1599817763912286208

SchmidtPaul commented 3 months ago

Found a solution using {marquee} instead. See updated Stackoverflow Post above or this post on LinkedIn