Highlighting bar in barplot
To create automated color in bars we use the fill property of the ggplot2 plot. We use a vector with the same value for all the bars except the one that needs to be highlighted.
R
# Create sample data set.seed (5642) sample_data <- data.frame (name = c ( "Geek1" , "Geek2" , "Geek3" , "Geek4" , "Geeek5" ) , value = c (31,12,15,28,45), highlight= c (0,0,1,0,0) ) # Load ggplot2 package library ( "ggplot2" ) # Create bar plot plot<- ggplot (sample_data, aes (name, value, fill=highlight)) + geom_bar (stat = "identity" ) plot |
Output:
How to Highlight a Bar in Barplot in R?
In this article, we will discuss how to highlight a bar in barplot in R Programming language.
First, let’s create a basic barplot with no bars highlighted using ggplot2.
R
# Create sample data set.seed (5642) sample_data <- data.frame (name = c ( "Geek1" , "Geek2" , "Geek3" , "Geek4" , "Geeek5" ) , value = c (31,12,15,28,45), highlight= c (0,0,1,0,0) ) # Load ggplot2 package library ( "ggplot2" ) # Create bar plot plot<- ggplot (sample_data, aes (name,value)) + geom_bar (stat = "identity" ) plot |
Output: