giordano
giordano

Reputation: 3152

Thousand separator in label of x or y axis

I would like to have pretty labels on the y-axis. For example, I prefer to have 1,000 instead of 1000. How can I perform this in ggplot? Here is a minimum example:

x <- data.frame(a=c("a","b","c","d"), b=c(300,1000,2000,4000))
ggplot(x,aes(x=a, y=b))+
               geom_point(size=4)

Thanks for any hint.

Upvotes: 27

Views: 25548

Answers (2)

George Shimanovsky
George Shimanovsky

Reputation: 1956

Prettify thousands using any character with basic format() function:

Example 1 (comma separated).

format(1000000, big.mark = ",", scientific = FALSE)
[1] "1,000,000"

Example 2 (space separated).

format(1000000, big.mark = " ", scientific = FALSE)
[1] "1 000 000"

Apply format() to ggplot axes labels using an anonymous function:

ggplot(x, aes(x = a, y = b)) +
        geom_point(size = 4) +
        scale_y_continuous(labels = function(x) format(x, big.mark = ",",
                                                       scientific = FALSE))

Upvotes: 10

Sandy Muspratt
Sandy Muspratt

Reputation: 32789

With the scales packages, some formatting options become available: comma, dollar, percent. See the examples in ?scale_y_continuous.

I think this does what you want:

library(ggplot2)
library(scales)

x <- data.frame(a=c("a","b","c","d"), b=c(300,1000,2000,4000))

ggplot(x, aes(x = a, y = b)) + 
  geom_point(size=4) +
  scale_y_continuous(labels = comma)

Upvotes: 42

Related Questions