Search code examples
rggplot2scalegeom-bar

How can I change the scale of the y axis in a barplot in ggplot2 to thousands?


I am using this code:

ggplot2::ggplot(DATAFRAME, aes(x = as.factor(VARIABLE))) + ggplot2::geom_bar()

to plot the number of occurences in each level of the variable VARIABLE in the data frame DATAFRAME. However, it is quite a long data frame, so I would like to have the counts in thousands instead of units. Does anybody know how to do this?


Solution

  • You can use a custom function as a formatter for the labels. Just add this to your plot

    + scale_y_continuous(name = "Count (thousands)",
        labels = function(y) y / 1000)
    

    For a reproducible example:

    ggplot(data.frame(x = 1:2, y = 3:4 * 1000)) + 
        geom_point(aes(x, y)) +
        scale_y_continuous(
            name = "Axis in thousands",
            labels = function(x) x / 1000
    )
    

    If you want to get fancy, you could even paste "k" onto the end of the numbers:

    labels = function(x) paste0(x / 1000, "k")