When making a graph, ggplot2
has a lot of sensible defaults for scales that require extra work when trying to achieve the same result using scales
.
An example:
library("ggplot2")
ggplot(mtcars, aes(drat, mpg)) + geom_point()
Note that this plot has one digit behind the decimal mark.
However, I live in the Netherlands and we're used to using a comma as decimal mark. This is easily done within scale_x_continuous
:
ggplot(mtcars, aes(drat, mpg)) +
geom_point() +
scale_x_continuous(labels = scales::label_number(big.mark = ".", decimal.mark = ","))
What bugs me about this solution is that this also increases the number of digits: there's an extra, rather unnecessary, 0 at the end of each label. Of course, this can also be solved within scales::label_number()
, by setting accuracy = 0.1
but that requires iteration (plotting and re-plotting to set the more sensible number of digits).
Is there an option to fix the default decimal mark used by ggplot? I'm looking for a solution where
ggplot(mtcars, aes(drat, mpg)) +
geom_point()
returns the same plot as
ggplot(mtcars, aes(drat, mpg)) +
geom_point() +
scale_x_continuous(labels = scales::label_number(
big.mark = ".",
decimal.mark = ",",
accuracy = 0.1
))
The key seems to be that format
(from base R) and scales::number
use different rules. We can revert to using format
...
myf <- function(x, ...) format(x, big.mark = ".", decimal.mark = ",", ...)
ggplot(mtcars, aes(drat, mpg)) +
geom_point() +
scale_x_continuous(labels = myf)
If you want to make these labels the global default I think you can do this:
scale_x_continuous <- function(..., labels = myf) {
do.call(ggplot2::scale_x_continuous, c(list(...), labels = labels))
}