Brandon
Brandon

Reputation: 1904

Use custom labeling function for labeling y axis in ggplot

I'm trying to create a custom function for making labels within ggplot. For example, I can use labels = scales::percent within scale_y_continuous() to format the y axis using percentage sign. However, I would like more control over the labeling function.

> mydf <- data.frame(a = 1:9,
+                    b = 1:9 / 10)
> mydf
  a   b
1 1 0.1
2 2 0.2
3 3 0.3
4 4 0.4
5 5 0.5
6 6 0.6
7 7 0.7
8 8 0.8
9 9 0.9
> ggplot(mydf) + geom_point(aes(x = a, y = b)) + scale_y_continuous(labels = scales::percent)

The documentation for scale_y_continuous() suggests that it is possible to create a custom function that can take in breaks and output labels, but there is no demonstration of this in the documentation.

labels One of:

NULL for no labels

waiver() for the default labels computed by the transformation object

A character vector giving labels (must be same length as breaks)

A function that takes the breaks as input and returns labels as output

Upvotes: 3

Views: 2575

Answers (3)

eipi10
eipi10

Reputation: 93851

Depending on how much customization you need, you might still be able to use the built-in functions. For example, to get percent labels with three decimal places, you could do:

library(ggplot2)
library(scales)

ggplot(mydf, aes(a, b)) + 
  geom_point() + 
  scale_y_continuous(labels=percent_format(accuracy=0.001))

enter image description here

Upvotes: 1

Simon Woodward
Simon Woodward

Reputation: 2026

Like this.

library(tidyverse)

mydf <- data.frame(a = 1:9, b = 1:9 / 10)

mylabels <- function(breaks){
    labels <- sprintf("%i%%", breaks*100) # make your labels here
    return(labels)
}

ggplot(mydf) + 
    geom_point(aes(x = a, y = b)) + 
    scale_y_continuous(labels = mylabels)

Created on 2019-05-06 by the reprex package (v0.2.1)

Upvotes: 4

Brandon
Brandon

Reputation: 1904

Ah, I managed to figure it out. For example, the function below allows me to control the number of decimal places while also converting values into percentages.

my_func <- function(x, decimals = 1) {
  fmt <- paste0("%.", decimals, "f") # eg "%.3f"
  num_string <- sprintf(fmt, 100*x)
  final_string <- paste0(num_string, "%")
  return(final_string)
}

ggplot(mydf) + 
  geom_point(aes(x = a, y = b)) + 
  scale_y_continuous(labels = function(i) my_func(i, decimals = 0))

Upvotes: 4

Related Questions