Home > OS >  How to customize bar plot color using base barplot in R
How to customize bar plot color using base barplot in R

Time:12-10

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?

CodePudding user response:

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

  • Related