How to customize bar plot color using base barplot in R

Advertisements
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?

>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

Leave a ReplyCancel reply