wilkelab / ggtext

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

Feature request / offer: legend keys with markdown formatting #111

Open teunbrand opened 6 months ago

teunbrand commented 6 months ago

Hi Claus and Brenton,

I'm interested in using text keys to display the labels of a colour/fill scale. I think it would be neat if there were a draw_key_markdown() or draw_key_richtext() function to handle formatting of such keys. For example, in the plot below I'd like the 'Iris' part of the label to be in black, and the species part in the appropriate colour and the whole label in italics.

library(ggplot2) # dev version

ggplot(iris, aes(Sepal.Width, Sepal.Length, colour = Species)) +
  geom_point(key_glyph = 'text') +
  scale_colour_discrete(
    labels = NULL,
    guide = guide_legend(override.aes = list(
      label = paste0(
        "<i><span style='color:black'>Iris</span> ", 
        c("setosa", "versicolor", "virginica"), "</i>"
      ),
      size = 11 / .pt, hjust = 0
    ))
  )

Created on 2023-12-15 with reprex v2.0.2

I'm well aware that there are other options available, such as formatting the scale's labels field, but I'm looking for legend key functions specifically. If this is something that you find appropriate for {ggtext}, I'm reasonably confident I can whip up a PR to consider.

clauswilke commented 6 months ago

Sure, go ahead. Shouldn't be difficult to write.