Home > Net >  How to increase space between the given two stacked bars?
How to increase space between the given two stacked bars?

Time:08-26

How to increase space between the given two stacked bars (e.g., between second and third stacked bars) for the following code? The rest space does not need to be changed. Thanks a lot!

library(ggplot2)
rm(list = ls())

Year      <- c(rep(c("2006-07", "2007-08", "2008-09", "2009-10"), each = 4))
Category  <- c(rep(c("A", "B", "C", "D"), times = 4))
Frequency <- c(168, 259, 226, 340, 216, 431, 319, 368, 423, 645, 234, 685, 166, 467, 274, 251)
Data      <- data.frame(Year, Category, Frequency)

ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency))  
  geom_bar(stat = "identity",width = 0.8)  
  geom_text(size = 3, position = position_stack(vjust = 0.5))

CodePudding user response:

You could change the xmin of your third bar and xmax of your second bar using ggplot_build. I changed it with 0.1 so you can modify that. Here is a reproducible example:

library(ggplot2)
library(dplyr)
Year      <- c(rep(c("2006-07", "2007-08", "2008-09", "2009-10"), each = 4))
Category  <- c(rep(c("A", "B", "C", "D"), times = 4))
Frequency <- c(168, 259, 226, 340, 216, 431, 319, 368, 423, 645, 234, 685, 166, 467, 274, 251)
Data      <- data.frame(Year, Category, Frequency)

p <- ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency))  
  geom_bar(stat = "identity")  
  geom_text(size = 3, position = position_stack(vjust = 0.5)) 

# Old plot
p

q <- ggplot_build(p)

# Here you can decide the distance between specific bars
q$data[[1]] <- q$data[[1]] %>%
  mutate(xmin = ifelse(x == 3, xmin   0.1, xmin),
         xmax = ifelse(x == 2, xmax - 0.1, xmax))

q <- ggplot_gtable(q)
# New plot
plot(q)

Created on 2022-08-26 with bar_with_space

  • Related