Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

ggplot2

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!

like image 839
Canovice Avatar asked Dec 23 '22 03:12

Canovice


2 Answers

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"))
like image 72
Roman Avatar answered May 24 '23 08:05

Roman


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)
like image 20
Moody_Mudskipper Avatar answered May 24 '23 09:05

Moody_Mudskipper