in R use `$` and `K` as a y-axis labels for thousands of dollars

Viewed 1891

This older stackoverflow question explains how to change your y-axis to K for thousands instead of ,000. It also explains how to put a dollar sign on the y-axis labels with scales::dollar. My trouble is in combining the two ideas in R:

library(tidyverse)
library(scales)
set.seed(200)
df <- tibble(Date = seq(as.Date("2018/1/1"), by = "month", length.out = 12),
             Values = c(runif(12, 200000, 800000)))

ggplot(df, aes(Date, Values)) + 
  geom_line() + 
  scale_y_continuous(label = unit_format(unit = "K", scale = 1e-3, sep = "")) + 
  # scale_y_continuous(labels = dollar) +  # line 10
  NULL

I can use either line 9 or line 10 above, but not both simultaneously. How do I incorporate both line 9 and 10 into a single line? I want to transfer, as an example, 115,000 into $115K.

1 Answers

You can use scales::dollar_format to achieve what you're going for:

ggplot(df, aes(Date, Values)) + 
  geom_line() + 
  scale_y_continuous(labels = scales::dollar_format(scale = .001, suffix = "K"))
Related