Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 - highlight min/max bar

Tags:

r

ggplot2

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" )
like image 900
SFun28 Avatar asked Mar 08 '26 23:03

SFun28


2 Answers

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

like image 51
rcs Avatar answered Mar 10 '26 14:03

rcs


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'))
like image 36
Ramnath Avatar answered Mar 10 '26 13:03

Ramnath