The scale_fill_brewer() function in R uses a range of colors from a set of palettes in the RColorBrewer package. It changes the fill color of ggplot2 plots, such as boxplots, bar plots, violin plots, dot plots, etc.
The scale_fill_brewer() function takes several arguments, including palette, which specifies the name of the color palette to use, type, which specifies whether the variable is continuous or discrete and direction, which controls the order of the colors in the palette.
scale_fill_brewer( ..., type = "seq", palette = 1, direction = 1, aesthetics = "fill" )
type: It is one of “seq” (sequential), “div” (diverging), or “qual” (qualitative)
palette: If a string will use that named palette. If a number will index into the list of palettes of the appropriate type. The list of available palettes can be found in the Palettes section.
direction: It sets the order of colors in the scale. If 1, the default colors are as output by RColorBrewer::brewer.pal(). If -1, the order of colors is reversed.
aesthetics: The character string or vector of character strings listing the name(s) of the aesthetic(s) that this scale works with.
…: Other arguments.
library(ggplot2) # Create a simple bar chart plot <- ggplot(data = diamonds, aes(x = cut, fill = clarity)) + geom_bar() # Apply the color palette from the RColorBrewer package plot + scale_fill_brewer(palette = "Set1")
In this code example, we applied the Set1 color palette from RColorBrewer to the fill aesthetic of the geom_bar() layer in the ggplot2 plot.
Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language.