2013-08-19 51 views
0

如何通過geom_bar()圖一個單獨的載體添加標籤?添加標籤GGPLOT2

a<-as.POSIXlt("2013-07-01 00:00:00",origin = "1960-01-01",tz="GMT") 
b<-as.POSIXlt("2013-07-08 00:00:00",origin = "1960-01-01",tz="GMT") 

week1<-sample(seq(as.numeric(a),by=60*60,length.out=200),200,T) 
week2<-sample(seq(as.numeric(b),by=60*60,length.out=200),200,T) 
times<-c(week1,week2) 
class(times)<-c("POSIXt","POSIXct") 
times<-as.POSIXlt(times,origin = "1960-01-01",tz="GMT") 
key<-sample(LETTERS[1:3],200,T) 
df<-data.frame(times=times,order=factor(rep(1:2,each=100)), key=key) 

p<-ggplot(df, aes(x=key, y=..count.. ,fill=key)) 
p<-p + geom_bar() 
p<-p + facet_wrap(~ order,ncol=2) 
p<-p + coord_flip() 
p 

我喜歡添加的每個密鑰值,其通過DF1 $ y所表示的數量:

df1<-ddply(df, .(key,order), summarize, y=length(key)) 
p<-p + geom_text(aes(label=df$1y), vjust=0) 

回答

1

可以通過使用data參數與不同的數據源添加的另一層。這裏的關鍵是,層映射到y軸不同 - geom_bar()由計數映射,而geom_text()df1(我假設y值映射 - 它可能是一些其他的價值,但是這似乎合乎邏輯)。這意味着你需要指定y =每個geom_裏面調用:

p <- ggplot(df, aes(x = key, fill = key)) 
p1 <- p + geom_bar(aes(y = ..count..)) + facet_wrap(~ order, ncol = 2) + 
    coord_flip() 
p2 <- p1 + geom_text(data = df1, aes(y = y + 5, label=y), vjust=0) 
p2 

enter image description here