Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to customize bar plot color using base barplot in R

data(iris)
barplot(iris$Sepal.Length, col = iris$Species)

enter image description here

The default colors are black, red, and green. How can I change these colors to, say, yellow, blue, orange? For the 3 iris species, respectively?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Create a named vector of colors and match the species with the vector’s names. Use this to index the colors vector.

data(iris)

colrs <- setNames(c("yellow", "blue", "orange"), unique(iris$Species))
i_colrs <- match(iris$Species, names(colrs))

barplot(iris$Sepal.Length, col = colrs[i_colrs])

barplot(iris$Sepal.Length, col = colrs[i_colrs], border = NA)

Created on 2022-12-10 with reprex v2.0.2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading