2016-09-14 16 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は困難です。一番簡単なことは、データセットをポジティブとネガティブの2つに分割し、それぞれのレイヤーを別々に追加することです。古典的な例はhereです。

正のy値に1つのテキストレイヤーを追加し、ネガティブに1つのテキストレイヤーを追加して、同じことをテキストで実行できます。

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") 
関連する問題