1

Typically to display axis values in different scales in ggplot2 we can use the following:

p + scale_y_continuous(labels = scales::unit_format(unit = "M", scale = 1e-6))

How can the same be done for geom_text labels? With commas we would do the following

p + geom_text(aes(y = y_val, x = x_val, label = scales::comma(value))) 

Is there a function analogous to comma for millions (ex: 100M)?

Cyrus Mohammadian
  • 4,982
  • 6
  • 33
  • 62
  • 1
    Does `p + geom_text(aes(y = y_val, x = x_val, label = scales::unit_format(unit = "M", scale = 1e-6)(value))) ` work? It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions. – MrFlick Jan 29 '21 at 19:34
  • So i actually tried the above and it seems the extra parenthesis `(value)` were not appreciated. I was hoping for a simple `comma` like function but sans that the above does work if applied to the dataframe and called as a new variable. – Cyrus Mohammadian Jan 29 '21 at 19:47
  • 1
    What do you mean by "not appreciated" Do you have a column named "value" in your data.frame? If not, what's the name of the column that has the value that you want to use as the text label? The `value` is just whatever column name you like. – MrFlick Jan 29 '21 at 19:49
  • The `unit_format` function returns a function. you can name it like `mill <- scales::unit_format(unit = "M", scale = 1e-6)` and then call `mill(c(1e6, 25e5))` or use that in your aes: `label = mill(value)` like you would any other function. – MrFlick Jan 29 '21 at 20:06
  • Yeah, I see how that works, naming the output of `unit_format` is the way to go – Cyrus Mohammadian Jan 29 '21 at 22:18

1 Answers1

1

Perhaps you could use paste within geom_text in a similar way to accomplish what you are asking?

library(ggplot2)
library(dplyr)


example_data <- tibble(
  foo = c(1000000, 2000000, 3000000, 4000000, 5500000),
  bar = c(1000000, 2000000, 3000000, 4000000, 5500000)
)

ggplot(example_data, aes(x = foo, y = bar)) +
  geom_point() +
  geom_text(aes(label = paste(round(foo / 1e6, 1), "M")))

Created on 2021-01-29 by the reprex package (v0.3.0)

Eric
  • 2,699
  • 5
  • 17