Reputation: 10441
I have created the following ggplot to highlight my issue:
mydf = data.frame(x = c(1,2,3,4,5), y = c(1,2,3,4,5))
ggplot(data = mydf) +
geom_point(aes(x = x, y = y)) +
scale_x_continuous(labels = scales::dollar_format()) +
scale_y_continuous(labels = scales::unit_format(unit = "M"))
which gives the following amazing, advanced ggplot graph:
My question is then simply - how can i make one axis have both the $ and M unit labels, so that the label shows as $1M $2M, etc. Is this possible? Is it also possible to reduce the gap between the number and the M sign, so that it shows 5M
instead of 5 M
Thanks as always!
Upvotes: 12
Views: 14578
Reputation: 88
scales::dollar_format()
has been superseded in favor of scales::label_currency()
. If your data was in dollars instead of millions of dollars, you could get the labels you want by combining scales::label_currency()
with scales::cut_short_scale()
:
mydf = data.frame(x = c(1,2,3,4,5)*1000000, y = c(1,2,3,4,5)*1000000)
ggplot(data = mydf) +
geom_point(aes(x = x, y = y)) +
scale_x_continuous(labels = scales::label_currency(scale_cut = cut_short_scale())) +
scale_y_continuous(labels = scales::label_currency(scale_cut = cut_short_scale()))
(I'm using scales
v1.3.0.)
Upvotes: 2
Reputation: 21
A method using y with unit_format() function to generate desired result - tick label y as "$1M", no gap between dollar and amount, no gap between amount and M:
mydf = data.frame(x = c(1,2,3,4,5), y = c(1,2,3,4,5))
ggplot(data = mydf) +
geom_point(aes(x = x, y = y)) +
scale_x_continuous(labels = scales::dollar_format()) +
scale_y_continuous(labels = scales::unit_format(unit = "M", prefix = "$", sep = "", accuracy = 1))
Using Roman's method - since y is using dollar format, results are same without prefix = "$" argument in dollar_format() function:
ggplot(data = mydf) +
geom_point(aes(x = x, y = y)) +
scale_x_continuous(labels = scales::dollar_format()) +
scale_y_continuous(labels = scales::dollar_format(suffix = "M"))
Upvotes: 1
Reputation: 47340
You can also define your own function:
ggplot(data = mydf) +
geom_point(aes(x = x, y = y)) +
scale_x_continuous(labels = f <- function(x) paste0("$",x,"M")) +
scale_y_continuous(labels = f)
Upvotes: 3
Reputation: 4989
Hacky, but works:
ggplot(data = mydf) +
geom_point(aes(x = x, y = y)) +
scale_x_continuous(labels = scales::dollar_format()) +
scale_y_continuous(labels = scales::dollar_format(prefix="$", suffix = "M"))
Upvotes: 15