Home > OS >  How to achieve an absolute percentage scale in ggplot with scales::label_percent?
How to achieve an absolute percentage scale in ggplot with scales::label_percent?

Time:01-10

I've got the following y-axis scale in ggplot

library(scales)

demo_continuous(c(-0.5, 0, 1))

I would like to have an absolute percentage scale. I figured out how to do an absolut scale using

demo_continuous(c(-0.5, 0, 1), labels = base::abs)

And I know how to do a percentage scale using

demo_continuous(c(-0.5, 0, 1), labels = scales::label_percent(accuracy = 0.1))

Thanks to this, I also figured out how to do an absolute percentage scale using

demo_continuous(c(-0.5, 0, 1), labels = function(x) scales::percent(base::abs(x)))

However, scales::percent is superseded by scales::label_percent and I did not figure out how to do the same thing using scales::label_percent instead of scales::percent.

Question: How to replicate function(x) scales::percent(base::abs(x)) using scales::label_percent?

CodePudding user response:

The label_percent() function creates a function itself that is then called on the numbers.

library(scales)
label_percent()
#> function (x) 
#> {
#>     number(x, accuracy = accuracy, scale = scale, prefix = prefix, 
#>         suffix = suffix, big.mark = big.mark, decimal.mark = decimal.mark, 
#>         style_positive = style_positive, style_negative = style_negative, 
#>         scale_cut = scale_cut, trim = trim, ...)
#> }
#> <bytecode: 0x7f86274ba7e0>
#> <environment: 0x7f86274b99a8>

So, you can just call that function in your labeling function as below:

demo_continuous(c(-0.5, 0, 1), labels = function(x)label_percent()(abs(x)))
#> scale_x_continuous(labels = function(x) label_percent()(abs(x)))

Created on 2023-01-09 by the reprex package (v2.0.1)

  • Related