NiuBiBang
NiuBiBang

Reputation: 628

ggplot2 geom_text - 'dynamically' place label over barchart

I have what I know is going to be an impossibly easy question. I am showing an average number of days by month using a bar chart, using the following example:

dat <- structure(list(Days = c("217.00", "120.00", "180.00", "183.00", 
    "187.00", "192.00"), Amt = c("1,786.84", "1,996.53", 
    "1,943.23", "321.30", "2,957.03", "1,124.32"), Month = c(201309L, 
    201309L, 201309L, 201310L, 201309L, 201309L), Vendor = c("Comp A", 
    "Comp A", "Comp A", "Comp A", "Comp A", 
    "Comp A"), Type = c("Full", "Full", 
    "Self", "Self", "Self", "Self"
    ), ProjectName = c("Rpt 8", 
    "Rpt 8", "Rpt 8", 
    "Rpt 8", "Rpt 8", 
    "Rpt 8")), .Names = c("Days", 
    "Amt", "Month", "Vendor", "Type", "ProjectName"
    ), row.names = c("558", "561", "860", "1157", "1179", "1221"), class =
    "data.frame")

ggplot(dat, aes(x=as.character(Month),y=as.numeric(Days),fill=Type))+
stat_summary(fun.y='mean', geom = 'bar')+
ggtitle('Rpt 8')+
xlab('Month')+
ylab('Average Days')+
geom_text(stat='bin',aes(y=100, label=paste('Avg:\n',..count..)))

Right now my labels are showing counts & showing up where ever i designate y.

I want to:

I've pretty thoroughly - and unsuccessfully - tried most of the other solutions on SO & elsewhere.

Upvotes: 0

Views: 1127

Answers (1)

NiuBiBang
NiuBiBang

Reputation: 628

Just got it:

means<-ddply(dat,.(Vendor,Type,Month), summarise, avg=mean(as.numeric(Days)))
ggplot(dat, aes(x=as.character(Month),y=as.numeric(Days),fill=Type))+
stat_summary(fun.y='mean', geom = 'bar')+
geom_text(data = means, stat='identity',
          aes(y=avg+7, label=round(avg,0),group=Type))

i realize there is code nearly identical to this sitting elsewhere. my error came in placing the round's 0 outside the correct closing parenthesis -- thus moving all my labels to 0 on x axis... DUH!

Upvotes: 2

Related Questions