简体   繁体   中英

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)

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

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.stack.imgur.com/rMMzl.png

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM