Reputation: 219
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
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())
Upvotes: 4