1

In ggplot2, I want to make bar_plot align with axis x (remove the blank area as attached image ). When use expand_limits(y=0), it seems can't work.Anyone can help ? Thanks!

library(tidyverse)
library(RColorBrewer)
data <- data.frame(category=c("a","b","c","d"),value=4:1)
data %>% ggplot(aes(category,value,fill=category))+
  geom_bar(stat='identity')+scale_fill_brewer(palette='Greens',direction=-1)+
  expand_limits(y=0)

enter image description here

anderwyang
  • 1,801
  • 4
  • 18
  • 2
    It's not `expand_limits` what you are looking for it's the `expand` argument, i.e. try with `scale_y_continuous(expand = c(0, 0, .05, .05))`. – stefan Feb 03 '22 at 06:05
  • Thanks for your replay. How to understand the four parmateres for expand ? it seems no help file for expand.Thanks – anderwyang Feb 03 '22 at 08:14
  • Related post: https://stackoverflow.com/q/13701347/680068 – zx8754 Feb 03 '22 at 08:28

1 Answers1

5

Use expansion:

ggplot(data.frame(category=c("a","b","c","d"),value=4:1),  
       aes(category, value, fill = category)) +
  geom_bar(stat='identity') +
  scale_y_continuous(expand = expansion(mult = c(0, 0.05)))

enter image description here

With mult = c(0, 0.05), this means that the bottom is not expanded (0) and the top is expanded 5% (which looks about like the default). If you set a length-1 arg mult=0, then both are set to the same (not expanded here). You can also use add= (same methodology) with or without mult=.

r2evans
  • 141,215
  • 6
  • 77
  • 149