Gabriel
Gabriel

Reputation: 81

How to add units on a scale using ggplot2?

I'm currently using ggplot to create a chart.

I would like to know how to add units on my scale (like a suffix).

This is the codes lines for the scale :

mean <- mean(DTA[, 2]) # column two mean from my data frame

scale_x_continuous(breaks = c(mean -10, mean - 5, mean, mean + 5, mean + 10))

So if mean = 100, the scale is : 90 95 100 105 110

How to add "%" ? (to obtain this : 90% 95% 100% 105% 110%)

I tried this code but it doesn't works :

scale_x_continuous(breaks = bquote(c(mean -10, mean - 5, mean, mean + 5, mean + 10)~. (%)))

Thank you

Upvotes: 3

Views: 4397

Answers (1)

Oliver
Oliver

Reputation: 8572

As the comments stated there are several ways of doing so. In any case what you want is to use the labels argument in the scale_*_continuous (or scale_*_discrete) to specify formatting. The simplest way is to use the scales package, which provides some easy-to-use formatting functions, such as percent and percent_format.

In ggplot2 you can specify formats in 2 ways. Manual labels eg. labels = c("30 %", "40 %", ...) and as a function labels = percent. Below I've illustrated how this can be done using the mtcars dataset

data("mtcars")
mtcars$RatioOfOptimalMpg <- with(mtcars, mpg / max(mpg)) 
scales::percent(mtcars$RatioOfOptimalMpg)[1:6]
#[1] "61.9%" "61.9%" "67.3%" "63.1%" "55.2%" "53.4%"
library(ggplot2)
ggplot(data = mtcars, aes(x = hp, y = RatioOfOptimalMpg)) + 
    geom_point() + 
    labs(y = "% of best mpg observed") + 
    scale_y_continuous(labels = scales::percent)

Image of mtcars ggplot with percentage scales

Now you might want to customize this formatting. In this case you can use scale_y_continuous(labels = scales::percent_format(...)) replacing ... with the formatting arguments. The scales package provides quite a few nifty functions for formatting discrete and continuous variables, and you'll find it mentioned here and there on SO.

Using this idea a simple method for creating any wished format is thus either explicitly writing out the labels

ggplot(data = mtcars, aes(x = hp, y = RatioOfOptimalMpg * 100)) + 
    geom_point() + 
    labs(y = "% of best mpg observed") + 
    scale_y_continuous(labels = paste0(RatioOfOptimalMpg * 100, " %"))

or similarly creating a function like scales::percent which would do the formatting for you

addPercent <- function(x, ...) #<== function will add " %" to any number, and allows for any additional formatting through "format".
    format(paste0(x, " %"), ...)
ggplot(data = mtcars, aes(x = hp, y = RatioOfOptimalMpg * 100)) + 
    geom_point() + 
    labs(y = "% of best mpg observed") + 
    scale_y_continuous(labels = addPercent)

Note in both cases I've multiplied my RatioOfOptimalMpg by 100, as my values are in decimal percentage.

Upvotes: 4

Related Questions