wilkelab / gridtext

Improved text rendering support for grid graphics in R
https://wilkelab.org/gridtext
Other
96 stars 17 forks source link

[FR] specify exact width of richtext_grob #19

Open pank opened 3 years ago

pank commented 3 years ago

I am trying to make left aligned, "box-like" axis.text.y labels (element_textbox would be ideal).

align_widths from ggtext seems to work well enough in simple cases and seems quite a bit nicer than element_text.
Alas, I use facets to split my labels into categories. This "breaks" align_widths, at least for my purposes.

It would be great if element_markdown and I guess ultimately richtext_grob, would have a width argument for when texts are e.g. split across facets.

An example follows. In the second graph, labels are no longer left aligned because they don't have the same widdth. This makes it look a bit more sloppy, IMO.

I figured this feature request belongs here more than on ggtext issue tracker, but I am happy to move it. I'm also happy to try to write a patch if you want.

library(ggplot2)
library(ggtext)
library(patchwork)
d <- data.frame(label = c("Lorem ipsum dolor sit amet",
                     "consectetur adipiscing",
                     "elit, sed do eiusmod tempor",
                     "incididunt ut labore et dolore magna aliqua",
                     "Ut enim ad"
                     ),
           group = c(1,1,2,2,3),
           x = 1)

g1 <- ggplot(d) + geom_point(aes(x,label)) +
    scale_y_discrete(labels = function(txt)gsub("\\n", "<br>", scales::wrap_format(15)(txt))) + 
    theme(strip.placement = "outside",
          strip.text.y.left = element_text(angle = 0, vjust=1, size = 14, color = "white"),
          strip.background.y = element_rect(color = "white", fill = "navy"),
          axis.text.y = element_markdown(lineheight = 1,
                                         size=12,
                                         halign=0,
                                         align_widths=TRUE,
                                         debug=TRUE))
g2 <- g1 + facet_grid(group ~ ., space="free_y", scales="free_y", switch="both", as.table = TRUE)
g1 + g2

image