2013-08-19 4 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_text()df1y 값으로 매핑되는 반면 (geom_bar()은 카운트로 매핑 됨) - 다른 값일 수도 있지만 이것이 논리적 인 것으로 보입니다.).

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

: 즉, 각 geom_ 전화 내부 y =를 지정해야 의미