When using ggplot
on objects with large number of groups (e.g. n > 14), most palettes are not able to cope. The function colorRampPalette
is able to extend the range, but to embed it in the scale_fill_manual
, you would need to know the number of unique groups.
Is there a way to automatically extract the number of colours required from ggplot
directly? I have provided an example below, and to make the palette work, I have had to add the number of groups (14) as an argument to scale_fill_manual(values = palette_Dark2(14))
.
Plot using scale_fill_brewer
df <- data.frame(group = paste0("Category", 1:14),
value = 1:28)
library(ggplot2)
ggplot(df, aes(x = group, y = value, fill = group)) +
geom_bar(stat = "identity") +
scale_fill_brewer(palette = "Set1")
Warning message: In RColorBrewer::brewer.pal(n, pal) : n too large, allowed maximum for palette Set1 is 9 Returning the palette you asked for with that many colors
Plot using custom palette
Here I have specified a new colour palette before the plot, which is a colour ramp with 14 steps.
library(RColorBrewer)
palette_Dark2 <- colorRampPalette(brewer.pal(14, "Dark2"))
I then use this in the plot as follows:
ggplot(df, aes(x = group, y = value, fill = group)) +
geom_bar(stat = "identity") +
scale_fill_manual(values = palette_Dark2(14))
Update:
I tried to use length(unique(group))
to extract the number of unique groups but obtained an error message
Error in unique(group) : object 'group' not found
In the attempt of using length(unique(df$group))
, the error message is:
Error: Insufficient values in manual scale. 14 needed but only 1 provided. In addition: Warning message: In brewer.pal(length(unique(df$group)), "Dark2") :n too large, allowed maximum for palette Dark2 is 8 Returning the palette you asked for with that many colors
length(unique(df$group))
into thebrewer.pal()
command? LikecolorRampPalette(brewer.pal(length(unique(df$group)), "Dark2"))
– Felixlength(unique(group))
would return error message of "object 'group' not found". – Phil Wu