Search code examples
rggplot2graphfiguregeom-bar

How to differentiate samples on the x axis using ggplot in r


I have created a geom_bar plot using ggplot which has 14 individual samples along the x axis. These samples belong to different groups and I was hoping to add an element to the figure which would indicate which samples belong to each group.

For example in this output figure, samples HH11-HH21 belong to one group, HH21-35 belong to another and the remainder belong to another group. For example in this output figure, samples HH11-HH21 belong to one group, HH21-35 belong to another and the remainder belong to another group

Is if possible to add a coloured bar along the top of the figure which indicates which group the samples belong to?

This is the code I used to generate this figure:

ggplot(full_table_top30, aes(x = variable, y = value, fill = Genus)) +
  geom_bar(position = "fill", stat = "identity") +
  scale_fill_manual(breaks = Genus2, values = Cb64k) +
  scale_y_continuous(labels = percent_format()) +
  theme(legend.position = "right", text=element_text(size=12),
        axis.text.x = element_text(angle=90, vjust=1)) +
  guides(fill = guide_legend(ncol=2)) +
  ggtitle(opt$gtitle) +
  xlab("Patient ID") + ylab("Relative activity")

Solution

  • We don't have your data, but I think what you're looking for is facet_grid(). If we build some data:

    df <- tibble(class = rep(c("H1", "H2", 
                               "H3", "H4"), each = 3),
                 variable = rep(c("V1","V2",
                                  "V3"), 4),
                 value = sample(20:50, 12),
                 group = ifelse(class == "H1" | class == "H2", 
                                "Group 1", "Group 2"))
    

    Then plot it:

    df %>% 
      ggplot(aes(x = class, y = value, fill = variable)) + 
      geom_bar(stat = "identity") + 
      facet_grid(cols = vars(group), scales = "free_x") +
      theme(panel.spacing = unit(0, "lines"))
    

    enter image description here Within facet_grid() you specify your group variable, and use "free_x" so that each facet only contains variables for the specific group. Finally, faceting adds space between the two plots. You can delete this by zeroing out the panel spacing.

    And you can change the color of the facets with the following: theme(strip.background=element_rect(fill="#ff0000", color = NA))

    Addendum

    mutate(full_table_top30, group = ifelse(variable == "HH11" | variable == "HH12" | 
                                                variable == "HH15" | variable == "HH21", "PEDIS2", 
                                              ifelse(variable == "HH1" | variable == "HH18" | 
                                                variable == "HH20" | variable == "HH24" | 
                                                variable == "HH34" | variable == "HH35", 
                                                "PEDIS3", "PEDIS4")))