Creating color palettes in R (2024)

[This article was first published on Let's talk about science with R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

There are several color palettes available in R such as rainbow(), heat.colors(), terrain.colors(), and topo.colors(). We can visualize these as 3D pie chartsusing theplotrix R package.

# Let's create a pie chart with n=7 colors using each palettelibrary(plotrix)sliceValues <- rep(10, 7) # each slice value=10 for proportionate slicespie3D(sliceValues,explode=0, theta=1.2, col=rainbow(n=7), main="rainbow()")# Let's create a figure with all 4 base color palettespar(mfrow=c(1, 4))pie3D(sliceValues,explode=0, theta=1.2, col=rainbow(n=7), main="rainbow()")pie3D(sliceValues,explode=0, theta=1.2, col=heat.colors(n=7), main="heat.colors()")pie3D(sliceValues,explode=0, theta=1.2, col=terrain.colors(n=7), main="terrain.colors()")pie3D(sliceValues,explode=0, theta=1.2, col=topo.colors(n=7), main="topo.colors()")

Creating color palettes in R (1)

Other popular color palettes include the RColorBrewerpackage that has a variety of sequential, divergent andqualitative palettes and the wesandersonpackage that has color palettes derived from his films.

library(RColorBrewer)# To see all palettes available in this packagepar(mfrow=c(1, 1))display.brewer.all()# To create pie charts from a sequential, divergent and qualitative RColorBrewer palettepar(mfrow=c(1, 4))pie3D(sliceValues,explode=0, theta=1.2, col=brewer.pal(7, "RdPu"), main="Sequential RdPu")pie3D(sliceValues,explode=0, theta=1.2, col=brewer.pal(7, "RdGy"), main="Divergent RdGy")pie3D(sliceValues,explode=0, theta=1.2, col=brewer.pal(7, "Set1"), main="Qualitative Set1")# And add pie chart with a wes_anderson palette# we will only use 5 slices in the example since the Darjeeling palette only has 5 colorslibrary(wesanderson)pie3D(sliceValues[1:5],explode=0, theta=1.2, col=wes_palette("Darjeeling2"), main="Darjeeling2")

Creating color palettes in R (2)You can also create your own color palettes in Rwith your colors of choice with thecolors() function or creating a vector with the color names.A great review and cheat sheet for R colors can be found athttp://research.stowers-institute.org/efg/R/Color/Chart/.

# To get an idea of the colors availablehead(colors())length(colors()) # 657# To see all 657 colors as a color chart you can source the R script to generate a pdf version in your working directory

Creating color palettes in R (3)

# We can create choose a palette based on the R chart as follow:mycols <- colors()[c(8, 5, 30, 53, 118, 72)] ## or you could enter the color names directly# mycols <- c("aquamarine", "antiquewhite2", "blue4", "chocolate1", "deeppink2", "cyan4")# You could also get and store all distinct colors in the cl object and use the sample function to select colors at randomcl <- colors(distinct = TRUE)set.seed(15887) # to set random generator seedmycols2 <- sample(cl, 7)

You can also create color palettes with hex color codes.A great example of this is to work with popular color palettes available on the http://www.colorcombos.comwebsite. This website has various palettes you can choose from and even derivecolor palettes from your favorite websites. For example, let’s grabthe color palette from the rjbioinformatics.com website athttp://www.colorcombos.com/grabcolors.html.

Creating color palettes in R (4)

After entering the URL of ourwebsite, wewillreceive thehex codes for thecolorscheme used onthe website.

Creating color palettes in R (5)

We can even export the colors as little pencilsCreating color palettes in R (6)

Creating color palettes in R (7)

You can also choose from hundred of color schemes based on yourcolor of choice. For example, we will also create a color palette based onthe color olive – ColorCombo382.

Creating color palettes in R (8)

# For the rjbioinformatics.com color palettemycols3 <- c("#c6d4e1", "#2f2016", "#fcfaea", "#456789")# For ColorCombos382 palettemycols4 <- c("#C3D938", "#772877", "#7C821E", "#D8B98B", "#7A4012")# Now to get the pie charts for the last four palettespie3D(sliceValues,explode=0, theta=1.2, col=mycols, main="colors()")pie3D(sliceValues,explode=0, theta=1.2, col=mycols2, main="sample(colors(distinct=TRUE)")pie3D(sliceValues[1:4],explode=0, theta=1.2, col=mycols3, main="rjbioinformatics.com color grab")pie3D(sliceValues[1:5],explode=0, theta=1.2, col=mycols4, main="ColorCombos382 colorcombos.com")

Creating color palettes in R (9)

We can also create a color palette with the colorRampPalette() to use for heatmaps and other plots.Forthis example, we will use the leukemia dataset available in the GSVAdata package, which corresponds to microarray data from 37 human acute leukemias where 20 of these cases are Acute lymphoblastic leukemia (ALL) and the other 17 are ALL’s with Mixed leukemia gene rearrangements. For more information on the study please seeArmstrong et al. Nat Genet 30:41-47, 2002.

library(GSVAdata)data(leukemia) # loads leukemia_eset# Create a matrix from the gene expression eset objectM1 <- exprs(leukemia_eset)# Get a matrix of the top 50 most variable probes accros the sampleslibrary(genefilter)topVarGenes <- head(order(-rowVars(M1)), 50)mat <- M1[ topVarGenes, ]mat <- mat - rowMeans(mat)# For sample annotation informationhead(pData(leukemia_eset))table(leukemia_eset$subtype)# Get sample group as a factor the ColSideColorsALLgroup <- as.factor(pData(leukemia_eset)[colnames(M1), 1])# Get the colors for the ALL subtypesidecols <- c("#4FD5D6", "#FF0000")# Here is a fancy color palette inspired by http://www.colbyimaging.com/wiki/statistics/color-barscool = rainbow(50, start=rgb2hsv(col2rgb('cyan'))[1], end=rgb2hsv(col2rgb('blue'))[1])warm = rainbow(50, start=rgb2hsv(col2rgb('red'))[1], end=rgb2hsv(col2rgb('yellow'))[1])cols = c(rev(cool), rev(warm))mypalette <- colorRampPalette(cols)(255)library("gplots") # for the heatmap.2 functionpar(mfrow=c(1,1))png(filename="Heatmap_Example.png", width=12, height=10, units = 'in', res = 300)heatmap.2(mat, trace="none", col=mypalette, ColSideColors=sidecols[ALLgroup],labRow=FALSE, labCol=FALSE, mar=c(6,12), scale="row", key.title="")legend("topright", legend=levels(ALLgroup), fill=sidecols, title="", cex=1.2)graphics.off()

Creating color palettes in R (10)

Now you are all set to work with and create your own awesome color palettes! Happy R programingCreating color palettes in R (11)


Creating color palettes in R (12) Creating color palettes in R (13)

Related

To leave a comment for the author, please follow the link and comment on their blog: Let's talk about science with R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Insights, advice, suggestions, feedback and comments from experts

As an expert and enthusiast, I am not a person but a program designed to assist with various tasks and provide information on a wide range of topics. While I have personal experiences or opinions, I have been trained on a diverse range of data, including scientific literature and programming resources, to generate responses that are accurate and informative.

In regards to the article you mentioned, it discusses various color palettes available in R for data visualization. The author demonstrates how to create 3D pie charts using different color palettes such as rainbow(), heat.colors(), terrain.colors(), and topo.colors(). The plotrix package is used to generate the pie charts. The article also introduces other popular color palettes like RColorBrewer and wesanderson packages, which provide a variety of sequential, divergent, and qualitative palettes.

The author shows how to create pie charts using color palettes from RColorBrewer and wesanderson packages. Additionally, the article mentions the option to create custom color palettes in R using the colors() function or by creating a vector with color names. It also provides links to resources for reviewing and selecting colors in R.

Furthermore, the article discusses the option of creating color palettes using hex color codes, and it provides an example of working with color palettes available on the colorcombos.com website. The author demonstrates how to grab the color palette from a specific website and export the colors.

Lastly, the article showcases how to create a color palette using the colorRampPalette() function, which is useful for heatmaps and other plots. It provides an example of creating a heatmap using the GSVAdata package and leukemia dataset, and demonstrates how to customize the color palette for the heatmap using the colorRampPalette() function.

Overall, the article provides a comprehensive overview of various color palettes available in R and demonstrates how to use them for data visualization. It offers examples and code snippets to help readers understand and implement the concepts discussed.

Creating color palettes in R (2024)
Top Articles
Latest Posts
Article information

Author: Pres. Lawanda Wiegand

Last Updated:

Views: 6004

Rating: 4 / 5 (51 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Pres. Lawanda Wiegand

Birthday: 1993-01-10

Address: Suite 391 6963 Ullrich Shore, Bellefort, WI 01350-7893

Phone: +6806610432415

Job: Dynamic Manufacturing Assistant

Hobby: amateur radio, Taekwondo, Wood carving, Parkour, Skateboarding, Running, Rafting

Introduction: My name is Pres. Lawanda Wiegand, I am a inquisitive, helpful, glamorous, cheerful, open, clever, innocent person who loves writing and wants to share my knowledge and understanding with you.