33

While making a bar plot with ggplot I run into troubles getting the preferred thousands separator. I would like thousands to be separated by a dot instead of a comma. Like this it gives no separator:

require(ggplot2)
require(scales) 
options(scipen=10)
D = data.frame(x=c(1,2),y=c(1000001,500000))
p = ggplot(D,aes(x,y)) + geom_bar(stat="identity") 
p

and like this it gives a comma:

p + scale_y_continuous(labels=comma)

How do you get a dot as thousands separator? I can't find documentation on which types of other labels exist besides some examples on http://docs.ggplot2.org/0.9.3.1/scale_continuous.html.

Thanks in advance,

Forza

Forzaa
  • 1,465
  • 4
  • 15
  • 27
  • What's `comma` in `labels=comma`? Its an undefined variable, thats what it is... – Spacedman Apr 24 '14 at 08:23
  • @Spacedman it works and it is well defined. You can also see an example of it being used in the official documentation. Do you have the newest version of ggplot? You need to use library(scales), btw. – Forzaa Apr 24 '14 at 08:29
  • 1
    Its from the `scales` package. I see your edit now. – Spacedman Apr 24 '14 at 08:34

4 Answers4

51
p + scale_y_continuous(labels=function(x) format(x, big.mark = ".", scientific = FALSE))
lukeA
  • 53,097
  • 5
  • 97
  • 100
  • Works like a charm, thanks! Didn't know you could pass on functions to labels as well, that's useful. – Forzaa Apr 24 '14 at 08:32
  • 1
    If you type `comma` you'll see that it is a function very similar to the answer given. Perhaps suggest to the `scales` package author a `dottedThousands` function? – Spacedman Apr 24 '14 at 08:37
  • Find the github repo for scales (if it exists), add new issue. Otherwise email maintainer. – Spacedman Apr 24 '14 at 12:08
  • 2
    I'd like to add, that it's often necessary to add the trim option (see here: http://stackoverflow.com/questions/14665461/european-french-thousand-separator-in-ggplot) to the function on the x axis, as the format might move the axis values to the right. Thus they do not align any longer. – Bouncner Feb 09 '16 at 13:56
18

this also works:

p + scale_y_continuous(labels = scales::comma)
12

Very good answer. As you are defining a thousands separator, it is better to also define the decimal separator as a comma, to avoid errors.

p + scale_y_continuous(labels=function(x) format(x, big.mark = ".", decimal.mark = ",", scientific = FALSE))
BMLopes
  • 546
  • 6
  • 10
0

An even simpler answer than the ones provided is:

p + scale_y_continuous(labels = scales::comma_format(big.mark = '.'))
NorthNW
  • 157
  • 6