Search code examples
rggplot2stacked-chart

How to standardise colours of bars in stacked bar charts?


So I am plotting a number of stacked bar charts on antibiotic use. The antibiotics included in each chart will differ between each individual dataset being plotted. So for example, in chart 1, 'antibiotic x' may be plotted as red, but in chart 2, it may be plotted as orange.

I was wondering if there is any way in which to standardise the colouring so that antibiotic x is the same colour across all charts I am plotting? This way it would make it easier to visualise if all antibiotic classes were the same across all charts.

Some example code for what I have used to plot one of the stacked bar charts is as followed;

datastack016 %>%
  mutate(Date = dmy(Date),
         Q = quarter(Date, with_year = TRUE)) %>%
  group_by(Q) %>% 
  summarise_if(is.numeric, sum, na.rm = TRUE) %>%
  gather(Key, Total, -Q) %>%
  ggplot(aes(Q, Total, fill = Key)) +
    geom_bar(stat = "identity") +
    scale_x_yearqtr(format = "%Y") + 
    ylab("Antibiotic Total (Grams)") + 
    xlab("Date (Quarters/Year)")`

Any help would be much appreciated! :)


Solution

  • You could define the colours as a named vector and pass that to scale_fill_manual. See code below (just substitute scale_colour_manual with scale_fill_manual):

    cols <- setNames(c("dodgerblue", "limegreen", "tomato"),
                     levels(iris$Species))
    
    ggplot(iris, aes(Sepal.Width, Sepal.Length, colour = Species)) +
      geom_point() +
      scale_colour_manual(values = cols)
    

    And now without one of the factors:

    ggplot(iris[iris$Species != "setosa", ],
           aes(Sepal.Width, Sepal.Length, colour = Species)) +
      geom_point() +
      scale_colour_manual(values = cols)
    

    enter image description here

    Note that cols still contains dodgerblue, but this is dropped from the legend since we don't have the first group (setosa).