2016-05-15 140 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 

此代碼將生成以下barplot。

enter image description here

正如所看到的,有兩個條和在y軸上的第一條的值是33(即,10 + 23)。我想避免這個增加。這意味着,我想看到三條而不是兩條。我怎樣才能做到這一點?

回答

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

然而,因爲這不能給出關於wid的好的情節酒吧的日,您可以擴展您的數據幀如下:

# 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") 

這給:

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)在底部。我看到你的結果並非如此。 a在前兩根杆的中間,b不在杆的中部。 –

+0

@HaseebMahmud查看更新,HTH。 – Jaap