R barplot() – Set Colors for Bars in Bar Plot
To set colors for bars in Bar Plot drawn using barplot() function, pass the required color value(s) for
col parameter in the function call.
col parameter can accept a single value for color, or a vector of color values to set color(s) for bars in the bar plot.
If single color value is passed for
col parameter, then the color of all bars will be set with this color.
If a vector is passed, whose length is equal to the the number of bars, then the bars will be set with the respective color from the vector.
In the following program, we set different colors for different bars in the bar plot by passing a vector of colors to
col parameter in barplot() function call.
height <- c(2, 4, 7, 5) barplot(height, col = c("red", "green", "yellow", "blue"))
If we pass a single value for
col parameter in barplot() function call, then this color value will be set for all the bars.
height <- c(2, 4, 7, 5) barplot(height, col = "yellow")
We can pass hex values in RGB or RGBA format for colors.
height <- c(2, 4, 7, 5) barplot(height, col = c("#eb8060", "#b9e38d", "#a1e9f0", "#d9b1f0"))
In this R Tutorial, we learned how to set specific colors for bars in Bar Plot using R barplot() function, with the help of examples.