Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
713 views
in Technique[技术] by (71.8m points)

r - Display an axis value in millions in ggplot

I have a chart where I am charting some very large numbers, in the millions. My audience is unlikely to understand scientific notation, so I'm hoping to label the y axis in something like "2M" for two million for example.

Here's an example. Showing the full value (scales::comma) is better than the scientific notation it defaults to, but is still a bit busy:

library(ggplot2)
ggplot(as.data.frame(list(x = c(0, 200,100), y = c(7500000,10000000,2000000))), 
       aes(x = x, y = y)) +
  geom_point() +
  expand_limits( x = c(0,NA), y = c(0,NA)) +
  scale_y_continuous(labels = scales::comma)

enter image description here

I don't want to rescale the data, since I will be including labels with the values of the individual data points as well.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I find scales::unit_format() to be more readable:

library(dplyr)
library(scales)
library(ggplot2)

as.data.frame(
  list(x = c(0, 200, 100), 
       y = c(7500000, 10000000, 2000000))) %>%
  ggplot(aes(x, y)) +
  geom_point() +
  expand_limits(x = c(0, NA), y = c(0, NA)) +
  scale_y_continuous(labels = unit_format(unit = "M", scale = 1e-6))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...