Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 want 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 using scales::label_percent instead of scales::percent.

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

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading