rggplot2scale-color-manual

change environment size on scale_colour_manual to assign colour to factors to use across multiples plots


I need to make 5 plots of bacteria species. Each plot has a different number of species present in a range of 30-90. I want each bacteria to always have the same color in all plots, therefore I need to set an assigned color to each name. I tried to use scale_colour_manual to create a color set but, the environment created has only 16 colors. How can I increase the number of colors present in the environment created?

the code I am using can be replicated as follow:

colour_genus <- stringi::stri_rand_strings(90, 5) #to be random names

nb.cols = nrow(colour_genus) #to set the length of my string
MyPalette = colorRampPalette(brewer.pal(12,"Set1"))(nb.cols) # the palette of choice
colGenus <- scale_color_manual(name = colour_genus, values = MyPalette)

The output formed contains only 16 values, so when I try to apply it to a figure with 90 factors, it complains I have only 16 values

abundance <- runif(90, min = 10, max = 100)
my_data <- data.frame(colour_genus, abundance)

p <- ggplot(my_data, aes(x = colour_genus, y= abundance)) +
  geom_bar(aes(color = colour_genus, fill = colour_genus), stat = "identity", position = "stack") +
  labs(x = "", y = "Relative Abundance\n") +
  theme(panel.background = element_blank())
p + theme(legend.text= element_text(size=7, face="bold"), axis.text.x = element_text(angle = 90)) + guides(fill=guide_legend(ncol=2)) + scale_fill_manual(values=colGenus)

The following error shows: Error: Insufficient values in manual scale. 90 needed but only 16 provided.

Thank you very much for your help.


Solution

  • When you know all your 90 bacci names in front of plotting, you can try.

    set.seed(123)
    colour_genus <- sort(stringi::stri_rand_strings(90, 5))#to be random names. I sorted the vector to illustrate the output better (optional). 
    MyPalette <- sample(colors(), length(colour_genus))
    # named vector for scale_fill
    names(MyPalette) <- colour_genus
    
    # data
    abundance <- runif(90, min = 10, max = 100)
    my_data <- data.frame(colour_genus, abundance)
    
    # two sets to show results
    set1 <- my_data[20:30,]
    set2 <- my_data[25:35,]
    ggplot(set1, aes(x = colour_genus, y= abundance)) +
      geom_col(aes(fill = colour_genus)) +
      scale_fill_manual(values = MyPalette)
    

    enter image description here

    ggplot(set2, aes(x = colour_genus, y= abundance)) +
      geom_col(aes(fill = colour_genus)) +
      scale_fill_manual(values = MyPalette)
    

    enter image description here