rggplot2bar-chart

Symmetric y-axis limits for barchart in ggplot2


I would like to make the y-axis of a bar chart symmetric, so that it's easier to see if positive or negative changes are bigger. Since otherwise this is a bit distorted. I do have working code although it's a bit clumsy and I thought it would be great if I could directly do this in the first ggplot() call. So as to say that ylim directly is symmetrical.

set.seed(123)
my.plot <- ggplot( data = data.table(x = 1:10,
                          y = rnorm(10,0, 2)), aes(x=x, y=y)) +
        geom_bar(stat="identity")

rangepull <- layer_scales(my.plot)$y
newrange <- max(abs(rangepull$range$range))
my.plot +
             ylim(newrange*-1, newrange)

Solution

  • What about this :

    library(ggplot2)
    library(data.table)
    set.seed(123)
    
    my.data = data.table(x = 1:10, y = rnorm(10,0, 2))
    
    my.plot <- ggplot(data = my.data)+aes(x=x, y=y) +
      geom_bar(stat="identity")+ylim((0-abs(max(my.data$y))),(0+max(abs(my.data$y))))
    
    my.plot