简体   繁体   中英

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM