Using label_percent() with the label argument of geom_text() and geom_label()

I noticed that there is an API change for labeling in the scales package, but I'm not clear on what the change should be to. For instance, using percentage formats has been the following:

library(scales)
library(ggplot2)

mydf <- tibble::tibble(perc = seq(0, 0.2, by = 0.05), cats = LETTERS[1:5])
ggplot(mydf, aes(x = cats, y = perc, label = percent(perc))) +
  geom_text()

But the help page for percent() has the following note:

Old interface
percent() and percent_format() are retired; please use label_percent() instead.

But how do I change the code above? The following leads to an error, and it's not clear from the set of examples in the help page how it should be used within geom_text() and geom_label():

ggplot(mydf, aes(x = cats, y = perc, label = label_percent(perc))) +
  geom_text()
#> Don't know how to automatically pick scale for object of type function. Defaulting to continuous.
#> Error: Aesthetics must be valid data columns. Problematic aesthetic(s): label = label_percent(perc). 
#> Did you mistype the name of a data column or forget to add stat()?
2 Likes

Labelling functions are designed to be used with the labels argument of ggplot2 scales.

It seems to me that these new functions are not meant to be used when mapping variables to the label aesthetic since they don't take an x argument so I think the old percent() is the only way to go while using the scales package. It would be nice if they could clarify what is their design choice for this use case.

2 Likes

label_percent returns a function, so it can be used like this:

ggplot(mydf, aes(x = cats, y = perc, label = label_percent()(perc))) +
  geom_text()

However, that seems like a confusing syntax and I'm not sure if usage within a geom is an intended use case. Typically, I do something like this:

ggplot(mydf, aes(x = cats, y = perc)) +
  geom_text(aes(label=sprintf("%1.1f%%", perc*100)))

To implement your own function, you could do:

pct = function(x, digits=1) {
  sprintf(paste0("%1.", digits, "f%%"), x*100)
}

ggplot(mydf, aes(x = cats, y = perc)) +
  geom_text(aes(label=pct(perc, 3)))

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.