Create Distinct Color Palette in R - GeeksforGeeks

23 May, 2021
In this article, we will discuss how to create a distinct color palette in R Programming Language. There are a number of ways to create color palettes in R programming, all such methods are discussed below. 
We’ll be using a package named grDevices, stands for graphics Devices, for making distinct color palettes in the first method. Here we’ll be using the colors function from the grDevices to make our palette.
Using colors() function: 
In this example we will make a pie chart using this very package. So, first we’ll be mentioning the number of colors, which we want in the palette. Then we’ll use the colors() function of this package, which contains a wide range of HCL(hue-chroma-luminance) based colors.
Example:
R
# number of colors in the paletteno_of_colors <- 10   # applying the colors function from # grDevices packagecolor_palette <- grDevices::colors()    # optional, for printing the hex # color codescolor_palette                           # pie function for drawing a pie chartpie(rep(1, no_of_colors), radius = 0.8,     col = color_palette,     main = "Color Palette using colors function")
Output:
Now, let’s say we wish to create a coloraturas’ palette of only Green color and its shades. We shall be following the above steps as usual for making this palette too, but the only change is that, we’ll be using the grep command here. grep is used to search or matches to argument pattern within each element of a character vector: they differ in the format of and amount of detail in the results.
Syntax:
grep(pattern, x, ignore.case = FALSE, perl = FALSE, value = FALSE,   fixed = FALSE, useBytes = FALSE, invert = FALSE)
Example:
R
# number of colors in the paletteno_of_colors <- 20        # applying the colors functioncolor_palette <- grDevices::colors()                            # prints all hex color codescolor_palette                                                   # grep command for matching the # pattern(character string --> green), palette <- color_palette[grep(  "green", grDevices::colors())]  # sample coloursgreen_palette <- sample(palette, no_of_colors)  # the list of the colours, which will # show up in the palettegreen_palette  # shows the created palettepie(rep(1, no_of_colors), col = green_palette,     main = "Green and its shades")
Output:
Using rainbow()
Here we’ll be making the color palette using the rainbow() function from grDevices package. rainbow() function is an in-built color palette which can be used in order to instantly generate some color vectors of desired length as per the parameter, and it returns the hexadecimal code of the colo available.
Syntax:
rainbow(variable name which stores the number of colors)
The entire process is just the same as before, only that we are using rainbow function over here.
Example:
R
# no. of colours in the paletteno_of_colors <- 15  # applying the rainbow functioncolorful_palette <- rainbow(no_of_colors)  # prints the hex color codescolorful_palette  # creates a pie chart of rainbow colourspie(rep(1, no_of_colors), col = colorful_palette,     main = "Rainbow Palette")
Output
Viridis package is a default color maps. It’s a series of color maps that are specially designed to improve graph readability for someone with common forms of color vision deficiency or color blindness.
This particular package consists of 8 color scales: “viridis”, being the topic name, and other such options with similar properties, which are listed below.
-> “magma”, –> option A
->“inferno”, –> option B
->“plasma”, –> option C
-> “viridis” –> default option D
->“cividis”, –> option E
-> “rocket”, –> option F
-> “mako”, –> option G
-> “turbo” –> option H
This viridis scale is for better understanding the color types, mentioned with their options.
Syntax:
viridis_pal(option = “option”)(variable storing the number of colors)
Example:
R
# installation of the viridis packageinstall.packages("viridis")  # loading of the librarylibrary("viridis")  # it may happen that the above 2 # lines of code pops out an error# saying viridisLite has to loaded# so to avoid that do load that # package toolibrary("viridisLite")  # number of colors in the paletteno_of_colors <- 10  # options represent the color types, # there are altogether 8 options.palette <- viridis_pal(option = "D")(no_of_colors)  # hex color codespalette  # represents colors in a pie chart mannerpie(rep(1, no_of_colors), col = palette, main = "viridis palette")
Output:
Also, if we wish to change the color pattern type of this palette, then we need to change the option(anything within A to H). Every part of the above code will remain the same except the option.
Example:
R
# loading of the librarylibrary("viridis")  # it may happen that the above# 2 lines of code pops out an# error saying viridisLite has # to loaded so to avoid that do# load that package toolibrary("viridisLite")  # number of colors in the paletteno_of_colors <- 10  # option A --> magmapalette <- viridis_pal(option = "A")(no_of_colors)  # hex color codespalette  # represents colors in a pie chart mannerpie(rep(1, no_of_colors), col = palette, main = "magma palette")
Output:
randomcoloR is an R language package for generating attractive and distinctive colors. The function distictColorPalette() generates optimally recognizable colors.
Syntax:
distictColorPalette(variable having the number of colors stored)
Example:
R
# installationinstall.packages("randomcoloR")library("randomcoloR")  # no. of colours in the paletteno_of_colors <- 15  # sample colorspalette <- distinctColorPalette(no_of_colors)       # hex color codespalette  # colors in the pie chartpie(rep(1, no_of_colors), col = palette,     main = "palette using randomcoloR package")
Output:
This package creates nice looking color palettes, especially for thematic maps. 
brewer.pal() makes the color palettes from ColorBrewer available as R palettes.
Syntax:
brewer.pal(n, name)
Parameter:
n: Number of different colors in the palette, minimum 3, maximum depending on palette.
name: A palette name from the lists below.
display.brewer.pal() displays the selected palette in a graphics window.
Syntax:
display.brewer.pal(n, name)
Parameter:
n: Number of different colors in the palette, minimum 3, maximum depending on palette.
name: A palette name from the lists below.
display.brewer.all() displays a few palettes simultaneously in a graphics window.
Syntax:
display.brewer.all(n=NULL, type=”all”, select=NULL, exact.n=TRUE, colorblindFriendly=FALSE)
Parameter:
n: Number of different colors in the palette, minimum 3, maximum depending on palette.
name: A palette name from the lists below.
type: One of the string “div”, “qual”, “seq”, or “all”.
select: A list of names of existing palettes
exact.n: If TRUE, only display palettes with a color number given by n.
colorblindFriendly: if TRUE, display only colorblind friendly palettes.
brewer.pal.info returns information about the available palettes as a dataframe. brewer.pal.info is not a function, it is a variable. This might change in the future.
 rownames Retrieve or set the row or column names of a matrix-like object.
Syntax:
rownames(x) <- value
There are 3 types of palettes namely: sequential, diverging, and qualitative.
Sequential palettes are suited to ordered data that progress from low to high. Lightness steps dominate the look of these schemes, with light colors for low data values to dark colors for high data values.
R
display.brewer.all(type="seq")
Output:
Diverging palettes put equal emphasis on mid-range critical values and extremes at both ends of the data range. The critical class or break in the middle of the legend is emphasized with light colors and low and high extremes are emphasized with dark colors that have contrasting hues. 
R
display.brewer.all(type="div")
Output:
Qualitative palettes do not imply magnitude differences between legend classes, and hues are used to create the primary visual differences between classes. Qualitative schemes are best suited to representing nominal or categorical data.
R
display.brewer.all(type="qual")
Output:
Example:
R
# installation of the package RColorBrewerinstall.packages("RColorBrewer")  # loading of the packagelibrary("RColorBrewer")  # extraction of color info# qual --> Qualitative color palettepalette5 <- brewer.pal.info[brewer.pal.info$category == "qual",]  # create vector with all colorspalette <- unlist(mapply(brewer.pal, palette5$maxcolors,                          rownames(palette5)))palette  # sample colorspalette_palette <- sample(palette, no_of_colors)  # colors with their hex codespalette_palette  # prints the pie chartpie(rep(1, no_of_colors), col = palette_palette,     main = "RColorBrewer Palette")
Output:
.
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R