blehman
blehman

Reputation: 1970

Can the bar labels appear centered on the appropriate bar in a combine bar/line graph?

Using the following data frame:

day <- c("Mon","Tues","Wed","Thurs","Fri","Sat","Sun","Week","Mon","Tues","Wed","Thurs","Fri","Sat","Sun","Week")
day <- factor(day, level=c("Mon","Tues","Wed","Thurs","Fri","Sat","Sun","Week"))
month<-c("Jan","Jan","Jan","Jan","Jan","Jan","Jan","Jan","Feb","Feb","Feb","Feb","Feb","Feb","Feb","Feb")
month<-factor(month,level=c("Jan","Feb"))
snow<-gl(1,16,labels=c("Y"))
snow<-factor(snow,levels=c("Y","N"))
count <- c(4,5,6,8,3,4,9,5.57,2,4,3,7,1,9,3,4.14)
d <- data.frame(day=day,count=count,month=month,snow=snow)

The bar labels center over week instead of the correct month's bar:

ggplot()+geom_line(data=d[d$day!="Week",],aes(x=day, y=count, group=month, colour=month))+geom_bar(data=d[d$day=="Week",],aes(x=day, y=count, fill=month),position="dodge", group=month)+facet_wrap(~snow,ncol=1,scales="free")+scale_x_discrete(limits=levels(d$day))+geom_text(data=d[d$day=="Week",],aes(x=day, y=count,label=paste(month),vjust=1.5),position="dodge",size=3)

Can the month labels appear centered on the appropriate bar?

Upvotes: 1

Views: 119

Answers (1)

Andrew
Andrew

Reputation: 38639

geom_text needs a specific dodge size to work:

p <- ggplot(data=d[d$day=="Week",], aes(x=day , y=count, fill=month)) + 
  geom_bar(position = "dodge", width = 0.8, stat="identity") +
  geom_text(aes(label=month, x=day, y=count), position=position_dodge(width=0.8), vjust=-.6, size=3) + 
  geom_line(data=d[d$day!="Week",], aes(x=day, y=count, group=month, colour=month)) + 
  facet_wrap(~snow,ncol=1,scales="free") + 
  scale_x_discrete(limits=levels(d$day))
p

Fixed graph

Upvotes: 1

Related Questions