ggplot2 icon indicating copy to clipboard operation
ggplot2 copied to clipboard

Label dictionaries

Open teunbrand opened this issue 1 year ago • 0 comments

I recently saw this tweet, which I thought was a nice suggestion, because it allows you to reuse labels without falling victims to typos and such. It still required a lot of manual management though.

Then, I realised we have several related issues/feature requests already, for example #4631 or #4313. However, I think having a label dictionary is perhaps a more elegant approach than hardcoding a path to retrieve labels from attributes (see also https://github.com/tidyverse/ggplot2/issues/4631#issuecomment-1102602900).

For the vanilla case, I think it should work something like this:

library(ggplot2)

label_dictionary <- c(
  displ = "Engine displacement [L]",
  hwy   = "Highway miles per gallon",
  "factor(cyl)" = "Number of cylinders" # Maybe I should be able to omit the function call?
)

# What I would like to specify
ggplot(mpg, aes(displ, hwy, colour = factor(cyl))) +
  geom_point() +
  labs(dict = label_dictionary)

# What I would want it to look like
ggplot(mpg, aes(displ, hwy, colour = factor(cyl))) +
  geom_point() +
  labs(!!!setNames(label_dictionary, c("x", "y", "colour")))

Created on 2023-02-05 with reprex v2.0.2

However, for the {Hmisc/tinylabels/labelled/sjlabelled} cases, we might be able to specify dict = derive() (or similar) to specifically instruct to lookup label names in the data.

teunbrand avatar Feb 05 '23 12:02 teunbrand