2

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?

Andrie
  • 176,377
  • 47
  • 447
  • 496
Mike Flynn
  • 1,025
  • 2
  • 12
  • 29

2 Answers2

4

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.

Mike Flynn
  • 1,025
  • 2
  • 12
  • 29
  • 2
    Your answer (and question) might be more helpful with an example using a minimal and reproducible dataset. – smillig Aug 15 '12 at 18:23
  • 4
    `scale_*` doesn’t seem to have a `formatter` argument in the current version of ggplot, and this code results in an error. Changing it to `labels = function…` works. – Konrad Rudolph Jan 24 '15 at 14:31
1

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)

Eric Leung
  • 2,354
  • 12
  • 25