user2872147
user2872147

Reputation: 219

Representing negative money in ggplot2 chart

I'm trying to represent negative money using R on a ggplot2 chart. I have large numbers (millions), so I'm transforming the numbers on the axis to 1M, 2M etc.

fmt <- function(){
function(x) format(paste("$",x/1000000,"M",sep=""),nsmall = 2,scientific = FALSE)
}

and then I use

scale_y_continuous(labels = fmt())

But for negative numbers, I want the negative sign in front of the currency symbol, so I suspect that there is a better way of doing this than using paste.

Upvotes: 2

Views: 248

Answers (1)

tonytonov
tonytonov

Reputation: 25638

fmt_mod <- function() {
     function(x) {
         y <- ifelse(x>=0, paste0("$", x/1000000, "M"), paste0("-$", -x/1000000, "M"))
         format(y, nsmall = 2, scientific = FALSE)
     }
}
ggplot(data.frame(x=1:5, y=(-2:2)*1e6), aes(x=x, y=y)) + 
  geom_point() + 
  scale_y_continuous(labels = fmt_mod())

enter image description here

Upvotes: 4

Related Questions