Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display an axis value in millions in ggplot

Tags:

r

ggplot2

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.

like image 720
Margaret Avatar asked Oct 02 '18 05:10

Margaret


People also ask

How do I change axis numbers in ggplot2?

Use scale_xx() functions It is also possible to use the functions scale_x_continuous() and scale_y_continuous() to change x and y axis limits, respectively.

How do I scale axis in R?

To change the axis scales on a plot in base R Language, we can use the xlim() and ylim() functions. The xlim() and ylim() functions are convenience functions that set the limit of the x-axis and y-axis respectively.

How do you change the scale from scientific notation to R?

First of all, create a vector and its plot using plot function. Then, use options(scipen=999) to remove scientific notation from the plot.

How do I change from standard form to scientific notation in Ggplot?

The scale_x_continuous() and scale_y_continuous() methods can be used to disable scientific notation and convert scientific labels to discrete form.


1 Answers

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

like image 101
João Avatar answered Sep 24 '22 06:09

João