Search code examples
rggplot2geom-bar

Create space and a vertical line between categories using geom_bar plot in ggplot2 in R


I have a bar chart in R using ggplot2 that shows different bars of different categories. Because some bar are = 0, I want to make a vertical line between the different categories so that they can be distinguished better visually.

I have already tried adding it through the panel.grid.major.x and panel.grid.minor.x arguments but that did not work. It would maybe also help if I can change the distance between the bars of the differnet categories instead of all of them when I do so with the width argument of geom_bar

Eg. in figure below: I want to add a vertical line and space between the purple bar of Cat 3 (Class 5) and the blue bar (Class 1) of Cat 4.

Example plot

Here is my code:

data <- categories.df
ggplot(data, aes(factor(Name, levels = c("Cat 1", "Cat 2", "Cat 3", "Cat 4", "Cat 5")), Count, fill = factor(SC_Class, levels = c("Class 1", "Class 2", "Class 3", "Class 4", "Class 5")))) +
    geom_bar(stat = "identity", position = position_dodge(width = 1), width = 0.8) +
    scale_fill_manual(values = c("#6C8EBF", "red", "#74767a", "orange","purple")) +
    labs(fill = "") +
    ylim(0,25) +
    xlab("Category") + ylab("Count") +
    theme(legend.position = c(1,1), legend.justification = c(1,1),
          axis.text.x = element_text(face = "bold", size=14),
          axis.text.y = element_text(face = "bold", size=14),
          axis.title.x = element_text(colour = "#6C8EBF", face = "bold", size =16),
          axis.title.y = element_text(colour = "#6C8EBF", face = "bold", size =16),
          panel.grid.major.y = element_line(size = 1, colour="#DAE8FC"),
          panel.grid.minor.y = element_line(colour="#DAE8FC"),
          panel.grid.major.x = element_blank(),
          panel.grid.minor.x = element_line(size = 1, colour="#DAE8FC"),
          plot.background = element_blank(),
          panel.background = element_blank(),
          panel.border = element_blank(),
          legend.text = element_text(size=12, face="bold")) 

How can I add a vertical line and spaces between the different categories using ggplot2 in R?


Solution

  • Use the position_dodge argument to your geom. I choose a more minimal example here, but you should be able to generalize it from there.

    test <- data.frame(
      a=1:9,
      b=rep(letters[1:3], 3),
      c=rep(letters[1:3], each=3)
    )
    
    ggplot(test, aes(y=a, x=b, group=c, fill=c)) + 
      geom_col(position="dodge") +
      geom_vline(xintercept = 1.5)
    

    (Based on this answer: ggplot side by side geom_bar())