I need to modify the scale of the y-axis in a ggplot2 graphic : I want to express the y-axis in thousands and not in units. For example, the labels have to be 0 ; 1,000 ; 2,000 ; 3,000 instead of 0 ; 1000000 ; 2000000 ; 3000000.
Please, don't tell me to divide my data by 1000 !
My question is the same as ggplot2 axis transformation by constant factor. But the solution provided here modifies the lables
parameter of the scale_y_continuous
function, whereas I need this parameter to be set to comma
. With this solution I get the following breaks : 0 ; 1000 ; 2000 ; 3000 ... Breaks are expressed in thousands and not in millions and this is a good point, but I loose the comma
labels. I want to see 1,000 ; 2,000 ; 3,000 and not 1000 ; 2000 ; 3000...
So modifying the lables
parameter of the scale_y_continuous
function isn't useful. That's why I think I have to work with the trans
parameter of the scale_y_continuous
function instead of the labels
parameter.
There are a lot of built-in transformation that match the trans
parameter and solve similar problems in the scales package (look at log_trans for example). So I tried to build my own homothetic transformation, with the code below.
library(ggplot2)
var0 <- c(1:100)
var1 <- 1000000*rnorm(100)
homothetic_breaks<- function (n = 5, base = 1000)
{
function(x) {
rng <- (range(x, na.rm = TRUE)/base)
min <- floor(rng[1])
max <- ceiling(rng[2])
if (max == min)
return(base*min)
by <- floor((max - min)/n) + 1
base*seq(min, max, by = by)
}
}
homothetic_trans <- function(base = 1000) {
trans <- function(x) x/base
inv <- function(x) x*base
trans_new(paste0("diviseur_par_", format(base)), trans, inv,
homothetic_breaks(base=base), domain = c(-Inf, Inf))
}
data <- data.frame(var0,var1)
p <- ggplot(data,aes(var0,var1))+geom_path()
p <- p + scale_y_continuous(trans=homothetic_trans,labels = comma)
p
When I run this code I get the following message : "Error: Input to str_c should be atomic vectors", and the breaks of the y axis arethe same as the ones I get when I run the following code :
library(ggplot2)
var1 <- 1000*rnorm(100)
var0 <- c(1:100)
data <- data.frame(var0,var1)
p <- ggplot(data,aes(var0,var1))+geom_path()
p