Search code examples
rggplot2colorsboxplotfill

How can I change the color based on my grouping value instead of fill value in ggplot in R?


I want to change the color of my boxplots based on their grouping value or individually instead of the fill value in ggplot. How can I do this? I need to define the fill variable to be able to get the groups subdivided into types, just as I intended, but I cannot seem to control the color anymore.

Here is some example data and how I define the plot:

library(ggplot2)

data <- data.frame( id    = rep(1:120),
                    group = as.factor(rep(1:3, times = 40)), 
                    type  = as.factor(rep(1:2, times = 60)), 
                    value = rnorm(120)+1)

ggplot(data, aes(x = group, y = value, fill = type)) +
  geom_boxplot(aes(fill = type)) +
  geom_point(aes(fill = type), position = position_jitterdodge(dodge.width = 0.65, jitter.width = 0.1, jitter.height = 0.1))

Which results in this image:

enter image description here

Now the colours are based on the "type" grouping. But I would like to control the 6 individual boxplots separately. For example, I want to colour them like this:

colors <- c("#b76e79", "#80a3dd",
            "#a5bf9f", "#e3f0cd",
            "#8a9a5b", "#ffdead")

Adding scale_fill_manual does not seem to work the way I want.

    ggplot(data, aes(x = group, y = value, fill = type)) +
      geom_boxplot(aes(fill = type)) +
      geom_point(aes(fill = type), position = position_jitterdodge(dodge.width = 0.65, jitter.width = 0.1, jitter.height = 0.1)) + 
scale_fill_manual(values = colors)

Any suggestions?


Solution

  • We create a new column by the interaction of 'group', 'type' and use that in scale_fill_manual

    library(dplyr)
    library(ggplot2)
    data <- data %>%
          mutate(grptype = interaction(group, type)) 
    gg <-  ggplot(data, aes(x = group, y = value, fill = grptype)) +
          geom_boxplot(aes(fill = grptype)) +
          geom_point(aes(fill = grptype), position = position_jitterdodge(dodge.width = 0.65, jitter.width = 0.1, jitter.height = 0.1)) 
          
    colors <- c("#b76e79", "#80a3dd",
                "#a5bf9f", "#e3f0cd",
                "#8a9a5b", "#ffdead")
      
    gg + 
        scale_fill_manual(name="grptype", 
                                 labels = levels(data$grptype),
                                 values = setNames(colors, levels(data$grptype))) +
    
    
         theme(legend.title = element_text(size=12, color = "black", face="bold"),
                                           legend.justification=c(0,1), 
                                           legend.position=c(0.05, 0.95),
                                           legend.background = element_blank(),
                                           legend.key = element_blank())
        
    

    -output

    enter image description here