2012-03-19 30 views
3

我開始提出一個可重複的例子來問另一個問題,甚至無法過去。無論如何,我正試圖將分類數據繪製成多面條形圖。所以我使用CO3創建了自己的數據集(代碼在底部)。只是繪製x本身似乎是正常的: enter image description hereggplot無法解釋的結果

但當我嘗試分面時會變得怪異。顯示一切都是平等的。 enter image description here

這是沒有意義的,因爲它會顯示每個子組有同等比例的出落得不是由數據的ftable證明:

    Type Quebec Mississippi 
outcome Treatment       
none nonchilled   7   6 
     chilled    4   7 
some nonchilled   6   4 
     chilled    5   5 
lots nonchilled   5   4 
     chilled    6   3 
tons nonchilled   3   7 
     chilled    6   6 

我在做什麼錯誤?

library(ggplot2) 
set.seed(10) 
CO3 <- data.frame(CO2[, 2:3], outcome=factor(sample(c('none', 'some', 'lots', 'tons'), 
      nrow(CO2), rep=T), levels=c('none', 'some', 'lots', 'tons'))) 
CO3 
x <- ggplot(CO3, aes(x=outcome)) + geom_bar(aes(x=outcome)) 
x 
x + facet_grid(Treatment~., margins=TRUE) 

with(CO3, ftable(outcome, Treatment, Type)) 

編輯:這個問題布賴恩描述的是一個容易發現自己,當你需要堆數據的採集。爲了克服此問題,直到ggplot的下一個版本(我假設哈德利是意識到了這個問題)我已經創建了一個愚蠢的小方便的功能,一個ID列添加到數據幀迅速:

IDer <- function(dataframe, id.name="id"){ 
    DF <- data.frame(c=1:nrow(dataframe), dataframe) 
    colnames(DF)[1] <- id.name 
    return(DF) 
} 

IDer(mtcars) 

回答

5

有一個bug在關於facet_grid()和重複行的ggplot2的0.9.0版本中。請參見https://github.com/hadley/ggplot2/issues/443

解決方法是添加一個虛擬列以打破重複。

CO3$dummy <- 1:nrow(CO3) 

ggplot(CO3, aes(x=outcome)) + 
    geom_bar(aes(x=outcome)) + 
    facet_grid(Treatment~., margins=TRUE) 

enter image description here

+0

謝謝,這是我逼瘋。不知道下一個ggplot2版本是否會出現問題 – 2012-03-19 21:45:37