hannes101
hannes101

Reputation: 2528

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)

Upvotes: 6

Views: 3111

Answers (3)

Jan
Jan

Reputation: 5254

You can do it drawing nothing with an inverted axis.

set.seed(123)
library(ggplot2)

dT <- data.frame(x = 1:10, y = rnorm(10,0, 2))

ggplot(dT, aes(x=x, y=y)) +
  geom_bar(stat="identity") + 
  geom_blank(aes(y = y * -1))

Created on 2024-12-30 with reprex v2.1.1

Upvotes: 0

M--
M--

Reputation: 28850

You may want to consider using ceiling:

set.seed(123)
library(ggplot2)
library(data.table)

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

This will give you:

 > my.plot

             https://i.sstatic.net/rMMzl.png

Upvotes: 1

MBnnn
MBnnn

Reputation: 308

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

Upvotes: 1

Related Questions