2013-05-11 78 views
1

使用下面的数据帧:条形标签可以在合并条形图/折线图中的相应条上出现居中吗?

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) 

酒吧标签中心超过一周,而不是正确的月份的酒吧:

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) 

可以每月标签显示为中心的适当栏上?

回答

1

geom_text需要一个特定的躲闪大小的工作:

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

+0

谢谢!这正是我期望实现的目标。我会投你一票,但我现在还没有在这个网站上。 – blehman 2013-05-12 00:30:17

+0

您可以选择此答案作为*答案与绿色复选标记,虽然:) – Andrew 2013-05-12 01:29:13

+1

您在ggplot()中定义了几个值,然后在geom_bar中使用stat =“identity”,然后正确引用geom_text中的标签。对于那些可能和我犯同样错误的人,请注意我最初使用的代码没有在ggplot()中定义任何内容,并导致geom_text发生故障(不会引发错误)。 – blehman 2013-05-12 04:27:00

相关问题