2017-07-07 233 views
1

我有這樣的情節添加標籤

dat = data.frame(group = c("A","A","B","B"), pct = c(.2,.3,.5,.4), subgroup = c("D","E","D","E"), x = c("Z","Z","Z","Z")) 


ggplot(data = dat, aes(x = factor(x), y =pct, fill= subgroup))+geom_bar(position = "stack", stat = "identity")+facet_wrap(~group) 

我要添加的每個層疊的z-也就是2種組分的總和,所以我建立一個銘牌數據幀之上的標籤和使用geom_text:

LABEL = data.frame(x = c("Z","Z"), y = c(.5,.9), group = c("A","B")) 
    ggplot(data = dat, aes(x = factor(x), y =pct, fill= subgroup))+geom_bar(position = "stack", stat = "identity")+facet_wrap(~group)+geom_text(aes(x= x,y=y ,label=labs), data = LABEL, vjust=-.2, size = 3) 

但由於分組是不是在數據幀我得到

: object 'subgroup' not found 

,但我不希望子錯誤作爲我繪製的標籤的數據框中的組是每個子組的總和。

上面的示例每個小平面都有一個堆疊條,但解決方案應適用於每個小平面圖任意數量的堆疊條。

+0

嘗試'geom_text'中的'inherit.aes = FALSE'。或者從全局的'ggplot'中刪除'fill'。 – aosmith

+0

這似乎不起作用。它是否適合你,你可以發佈代碼? – user3022875

回答

2

這是你想要的嗎?

dat = data.frame(group = c("A","A","B","B"), 
       pct = c(.2,.3,.5,.4), 
       subgroup = c("D","E","D","E"), 
       x = c("Z","Z","Z","Z")) 

LABEL = data.frame(x = c("Z","Z"), 
        y = c(.5,.9), 
        group = c("A","B")) 

ggplot(data = dat, aes(x = factor(x), y =pct)) + 
    geom_bar(aes(fill= subgroup), position = "stack", stat = "identity") + 
    facet_wrap(~group) + 
    geom_text(aes(x= x,y=y ,label=y), data = LABEL, vjust=-.2, size = 3)