Gongjin Lan
Gongjin Lan

Reputation: 55

How to increase space between the given two stacked bars?

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))

Upvotes: 2

Views: 70

Answers (2)

Quinten
Quinten

Reputation: 41397

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 reprex v2.0.2

Upvotes: 2

langtang
langtang

Reputation: 24732

Here is a quick hack, but colleagues with more expertise will no doubt provide more elegant answers:

  1. rename Year to something else, and add a new continuous Year that represents the gaps you want:
Data <- Data %>% rename(grp=Year) %>% mutate(Year = rep(c(1,2,4,5),each=4))
  1. add scale_x_continuous() indicating the breaks and labels you want.
scale_x_continuous(breaks=c(1,2,4,5),labels = unique(Data$grp))

bar_with_space

Upvotes: 1

Related Questions