Suraj
Suraj

Reputation: 36547

ggplot2 - highlight min/max bar

Without adding an extra column to the data.frame, is there a built-in way to highlight the min/max bar? In the following example, I'd like the Joe bar to be green (max) and the John bar to be red (min).

I'm sure this has been asked before, but I couldn't find when searching:

data= data.frame( Name = c("Joe","Jane", "John") , Value = c(3,2,1) )
ggplot(data=data)+geom_bar(aes_string(x="Name",y="Value"), stat="identity" )

Upvotes: 3

Views: 4816

Answers (4)

Chase
Chase

Reputation: 69171

Here's one option using logical indexing via which.min() and which.max():

ggplot(data, aes(Name, Value, stat = "identity")) + 
  geom_bar() +
  geom_bar(data = data[which.min(data$Value),], fill = "red") +
  geom_bar(data = data[which.max(data$Value),], fill = "green")

Upvotes: 1

John Colby
John Colby

Reputation: 22588

I think I would do it all in one go with an ifelse approach:

ggplot(data=data) + 
  geom_bar(aes_string(x="Name",y="Value", fill='factor(ifelse(Value==max(Value), 3, ifelse(Value==min(Value), 2, 1)))'), stat="identity" ) + 
  scale_fill_manual(values=c('gray20', 'red', 'green'), legend=F)

enter image description here

Upvotes: 1

Ramnath
Ramnath

Reputation: 55695

Here you go

ggplot(data, aes(Name, Value)) + 
 geom_bar(stat = 'identity') + 
 geom_bar(stat = 'identity', aes(fill = factor(Value)), 
   subset = .(Value %in% range(Value))) +    
 scale_fill_manual(values = c('red', 'green'))

Upvotes: 1

rcs
rcs

Reputation: 68839

You can use subsetting:

p <- ggplot(data=data)+
     geom_bar(aes(x=Name, y=Value), stat="identity") +
     geom_bar(data=subset(data, Value==min(Value)), aes(Name, Value),
              fill="red", stat="identity") +
     geom_bar(data=subset(data, Value==max(Value)), aes(Name, Value),
              fill="green", stat="identity")
print(p)

ggplot2 output

Upvotes: 5

Related Questions