2016-05-15 6 views
0

私のプロットに因子変数を追加しないでください。このデータについて考えてみましょう。ggplot:x軸の因子変数の加算を避ける

aa <- c(10, 12, 23) 
bb <- c("a", "b", "a") 
dataf <- data.frame(aa, bb) 

library(ggplot2) 
gplot <- ggplot(data=dataf, aes(x=bb, y=aa))+geom_bar(stat="identity") 
gplot 

このコードでは、次のようなバープロットが生成されます。

enter image description here

ご覧のように、そこに二つのバーであり、y軸における最初のバーの値は33(すなわち10 + 23)です。私はこの追加を避けたい。つまり、私は2つではなく3つのバーを見たいと思う。これどうやってするの?

dataf$rn <- ave(dataf$aa, dataf$bb, FUN = seq_len) 

、その後プロット:

ggplot(data=dataf, aes(x=bb, y=aa, fill=factor(rn))) + 
    geom_bar(stat="identity", position="dodge") 

与える:しかし

enter image description here

答えて

3

あなたは、各グループ内で一意の値を識別し、新しい列を作成することができますこれはウィジェットに関する素晴らしいプロットを与えないので棒の目、あなたは次のようにあなたのデータフレームを拡張することができます

# expand the dataframe such that all the combinations of 'bb' and 'rn' are present 
dfnew <- merge(expand.grid(bb=unique(dataf$bb), rn=unique(dataf$rn)), dataf, by = c('bb','rn'), all.x = TRUE) 
# replace the NA's with zero's (not necessary) 
dfnew[is.na(dfnew$aa),'aa'] <- 0 

をし、再度プロットします

ggplot(data=dfnew, aes(x=bb, y=aa, fill=factor(rn))) + 
    geom_bar(stat="identity", position="dodge") 

与える:

REPONSEで

enter image description here


にしますあなたのコメントは、あなたができる:

dataf$rn2 <- 1:nrow(dataf) 

ggplot(data=dataf, aes(x=factor(rn2), y=aa)) + 
    geom_bar(stat="identity", position="dodge") + 
    scale_x_discrete('', labels = dataf$bb) 

与える:あなたの返信用

enter image description here

+0

感謝。私が探しているのは、底に値(a、b、a)を持つ3つの均等に配置された列です。私はあなたの結果でそれがそうでないことを見る。 aは最初の2つのバーの中央にあり、bはバーの中央下にありません。 –

+0

@HaseebMahmudアップデート、HTHを参照してください。 – Jaap

関連する問題