When you have less colours defined with scale_fill_manual
than levels in a factor, ggplot2
complains with this error message :
# B
My workaround so far is to provide ggplot2 with more colours, should any more levels appear, like this:
# Basic definition of the plot
plot <- ggplot(s4r, aes(x=DIM, y=nbexpress, fill=DIM))
# Printing plot and options + faceting if any
plot + geom_bar(stat="identity", show_guide=FALSE) +
scale_fill_manual(values=c("#CC0000", "#006600", "#669999", "#00CCCC",
"#660099", "#CC0066", "#FF9999", "#FF9900",
"black", "black", "black", "black", "black"))
Just found a way to fill a palette to the needed size by picking from a given pool.
# count the needed levels of a factor
number <- nlevels(s4r$DIM)
# repeat the given colors enough times
palette <- rep(c("color1", "color2", ...), length.out = number)
# or, if you want a random distribution:
# if you want it random, but reproducable,
# backup .Random.seed, or set your own
set.seed(23)
palette <- sample(c("color1", "color2", ...), number, replace = TRUE)
scale_fill_manual(values=palette)