2016-09-14 108 views
1

我有這樣的條形圖:堆疊geom_bar問題與疊置條和標籤放錯了地方

group = c("A","A","B","B") 
value = c(25,-75,-40,-76) 
day = c(1,2,1,2) 
dat = data.frame(group = group , value = value, day = day) 

ggplot(data = dat, aes(x = group, y = value, fill = factor(day))) + 
    geom_bar(stat = "identity", position = "identity")+ 
    geom_text(aes(label = round(value,0)), color = "black", position = "stack") 

enter image description here

,我想堆疊酒吧和值出現。當我運行上面的代碼時,-76不在正確的位置(並且它看起來也不是75)。

任何想法如何讓數字出現在正確的位置?

+0

你應該注意的警告:'警告消息: 堆疊沒有明確定義,當YMIN = 0'即你正在做一個混亂的圖形! – alistaire

+0

如果你想要堆疊酒吧,你爲什麼在'geom_bar'中使用'position =「identity」'? – Axeman

+0

也@alistaire,我沒有得到這個警告,運行'2.1.0.9000'。 – Axeman

回答

1
ggplot(data=dat, aes(x=group, y=value, fill=factor(day))) + 
    geom_bar(stat="identity", position="identity")+ 
    geom_text(label =round(value,0),color = "black")+ 
    scale_y_continuous(breaks=c(-80,-40,0)) 

enter image description here

+1

OP會「喜歡堆疊的酒吧」。如果你不同意,你至少應該在答案中解釋。 – Axeman

0

堆疊負值和正值的混合是困難的GGPLOT2。最簡單的方法是將數據集分爲兩部分,一部分用於正數,另一部分用於負數,然後分別添加條形圖層。一個典型的例子是here

您可以對文本做同樣的事情,爲正y值添加一個文本圖層,爲負值添加一個文本圖層。

dat1 = subset(dat, value >= 0) 
dat2 = subset(dat, value < 0) 

ggplot(mapping = aes(x = group, y = value, fill = factor(day))) + 
    geom_bar(data = dat1, stat = "identity", position = "stack")+ 
    geom_bar(data = dat2, stat = "identity", position = "stack") + 
    geom_text(data = dat1, aes(label = round(value,0)), color = "black", position = "stack") + 
    geom_text(data = dat2, aes(label = round(value,0)), color = "black", position = "stack") 

enter image description here

如果使用GGPLOT2(2.1.0.9000)的當前開發版本,堆積似乎並沒有被在geom_text正常工作負值。如果需要,您總是可以「手動」計算文本位置。

library(dplyr) 
dat2 = dat2 %>% 
    group_by(group) %>% 
    mutate(pos = cumsum(value)) 

ggplot(mapping = aes(x = group, y = value, fill = factor(day))) + 
    geom_bar(data = dat1, stat = "identity", position = "stack")+ 
    geom_bar(data = dat2, stat = "identity", position = "stack") + 
    geom_text(data = dat1, aes(label = round(value,0)), color = "black") + 
    geom_text(data = dat2, aes(label = round(value,0), y = pos), color = "black")