Search code examples
rggplot2graph

How to add more than 2 colours to ggplot based on conditions?


My question is kind of like the one answered here: https://stackoverflow.com/a/12910865/16824530

However, while I would like all the negative values to be the same colour (e.g. dark blue), I would like for the positives to have different colours for each year. However, when I make a colour vector (such as the one below), I end up with each bar being a mix of all the colours in the vector.

vector <- ('2005'='pink', '2010'='green', '2011'='yellow')

I want to set each year that is positive a different colour while having all the negative years being just one colour.


Solution

  • You can extend the same idea from the post you referenced. Essentially, you can make a new variable that specifies between positive and negative values; however, rather than using "positive", we can use the year. Then, we can still use scale_fill_manual to set the colors. So, all negative values will be one color. Then, for each positive value, we can give a unique color.

    library(tidyverse)
    
    df %>% 
      mutate(grp = ifelse(value >= 0, as.character(variable), "negative")) %>% 
      ggplot(aes(x = variable, y = value, fill = grp)) + 
      geom_col() + 
      scale_fill_manual(values = c("negative" = "darkblue", "2002" = "blue", "2003" = "red", 
                                   "2004" = "orange", "2005" = "yellow", "2007" = "darkred",
                                   "2008" = "purple", "2009" = "green", "2012" = "darkgreen"))
    

    Output

    enter image description here

    Data

    df <- structure(list(Mealtime = c("Breakfast", "Breakfast", "Breakfast", "Breakfast", 
                                      "Breakfast", "Breakfast", "Breakfast", "Breakfast", 
                                      "Breakfast", "Breakfast", "Breakfast"), 
                         Food = c("Rashers", "Rashers", "Rashers", "Rashers", "Rashers", 
                                  "Rashers", "Rashers", "Rashers", "Rashers", "Rashers", "Rashers"), 
                         variable = structure(1:11, .Label = c("2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009", "2010", 
                                                               "2011", "2012"), class = "factor"), 
                         value = c(9.12, 9.5, 2.04, -20.72, 18.37, 91.19, 94.83,
                                   191.96,-125.3,-18.56, 63.85)),
                    row.names = c(NA, -11L), class = "data.frame")