With ggplot, use both unit_format and dollar_format from scales for tick text labeling
Asked Answered
V

4

12

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:

enter image description here

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!

Valladolid answered 12/10, 2018 at 22:13 Comment(0)
G
14

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"))
Galop answered 12/10, 2018 at 22:19 Comment(0)
A
3

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)
Amalamalbena answered 12/10, 2018 at 23:1 Comment(0)
F
1

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"))
Freemanfreemartin answered 26/3, 2022 at 6:47 Comment(0)
B
1

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.)

Bremerhaven answered 6/8 at 17:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.