'R ggplot2 changing units of an axis [duplicate]

Couldn't find this in a google search, so I thought I'd document it here.

My problem was I needed to change my y-axis labels to basis points, as opposed to standard units, but I couldn't find a way to fix this simple problem, I had my plot like this:

p <- ggplot(plotdat, aes(x = name, y = value, fill = variable)) + 
      geom_bar(position = "dodge")

but I kept trying to use this line but I kept getting an error.

p + scale_y_continuous(labels = function(x) as.character(x*10000), breaks = 10)
Error in as.vector(x, "character") : 
  cannot coerce type 'closure' to vector of type 'character'

How can I change the format of my y axis tick labels?



Solution 1:[1]

To format the axis tick labels, use the formatter option in scale_continuous. So:

p = p + scale_y_continuous(formatter = function(x) format(x*10000))

This should give you basis points.

Solution 2:[2]

The most voted answer here is a bit outdated and the formatter option doesn't exist anymore. It seems to be updated to labels instead. Below is a minimal example demonstration a before and after.

# Load libraries
library(dplyr)   # CRAN v1.0.6
library(ggplot2) # CRAN v3.3.5
library(scales)  # CRAN v1.1.1

# Without transformation
iris %>%
    ggplot(aes(Sepal.Length, Sepal.Width)) +
    geom_point()

# With transformation
iris %>%
    ggplot(aes(Sepal.Length, Sepal.Width)) +
    geom_point() +
    scale_y_continuous(labels = scales::label_comma(scale = 1000))

Created on 2022-02-03 by the reprex package (v2.0.1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mike Flynn
Solution 2 Eric Leung