2017-10-19 67 views
0

我嘗試獲取按「階段」分組的條形圖,並且每個階段的百分比應爲100%,因此總計爲200%。我嘗試了很多東西,但是我沒有成功。已經看過其他問題,但使用了非常不同的數據。如果有人能幫助我,那對我真的很有幫助。按變量分組的條形圖數量最多可達100%

BEAdata %>% 
    count(Phase = factor(Phase), Activities = factor(Activities)) %>% 
    mutate(pct = prop.table(n) * 100) %>% 
    ggplot(aes(x = Phase, y = n, fill = Activities)) + 
    geom_bar(stat = 'identity', position = 'dodge') + 
    geom_text(aes(y = n + .2, # nudge above top of bar 
       label = paste0(round(pct, 2), '%')), # prettify 
       position = position_dodge(width = .9), 
       size = 3) 

Output

Data

+0

你的下一個問題,請您dput的數據,我們會發現它更容易幫助,如果我們可以重新創建數據 – User632716

+0

也,你有沒有試過位置=「堆」? – User632716

+0

請以純文本形式提供數據而不是圖像(例如'dput(BEAdata)'的粘貼輸出)。 – neilfws

回答

0

你只需要一組添加到你做你的prop.table()計算之前。

唯一的變化是group_by(Phase)行。

require(dplyr) 
require(ggplot2) 

BEAdata %>% 
    count(Phase = factor(Phase), Activities = factor(Activities)) %>% 
    group_by(Phase) %>% 
    mutate(pct = prop.table(n) * 100) %>% 
    ggplot(aes(x = Phase, y = n, fill = Activities)) + 
    geom_bar(stat = 'identity', position = 'dodge') + 
    geom_text(aes(y = n + .2, # nudge above top of bar 
       label = paste0(round(pct, 2), '%')), # prettify 
       position = position_dodge(width = .9), 
       size = 3)