Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
716 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...