How can I mathematically transform the default labels on legend in ggplot?

Viewed 50

I have a 2D surface plot made with ggplot which I am colouring to show the value of it's third dimension. This data is wide-ranging in the Z direction, so I have log-transformed it before doing the interpolation for plotting.

I like the default choices that the plotting algorithm has chosen for the breaks. However, the labels for those breaks are now the log values.

The current code for the colouring is:

scale_fill_viridis(breaks = waiver(), labels = waiver())

waiver() is a flag to the underlying algorithm to use default values. Ideally, I'd like to do something like

scale_fill_viridis(breaks = waiver(), labels = sprintf("%.1f", 10^waiver()))

but that breaks with a Error in 10^my_breaks : non-numeric argument to binary operator error

How can I mathematically transform the default values for the labels into the values they would be prior to the log transform?

1 Answers

How about something like this:

your_function <- function(x){sprintf("%.1f", 10^as.numeric(x))}

labels = scales::trans_format("identity", your_function)

your_function will take the inverse of log10, effectively undoing the log transform. scales::trans_format will reformat the given label by applying whatever function it passed to it, in this case your_function.

You can of course define the reformatting function inside trans_format but in order to make things as clear as possible I've done it in two steps.

Related