2013-05-14 131 views
1

如果我有一個因素對我的變量y,並嘗試使用facet_gridgeom_hline我得到一個錯誤:水平線; Y軸的因素:GGPLOT2

p <- qplot(mpg, factor(sample(c("a", "b", "c", "d"), nrow(mtcars), T)), data=mtcars, facets = vs ~ am) 

hline.data <- data.frame(z = factor(c("a", "b", "c", "d")), vs = c(0,0,1,1), am = c(0,1,0,1)) 
p + geom_hline(aes(yintercept = z), hline.data) 

## > p + geom_hline(aes(yintercept = z), hline.data) 
## Error in x - from[1] : non-numeric argument to binary operator 

爲什麼我的錯誤,我怎麼能解決這個問題?

PS我可以通過它轉向數字爲解決這個問題:

hline.data <- data.frame(z = factor(c("a", "b", "c", "d")), vs = c(0,0,1,1), am = c(0,1,0,1)) 

qplot(mpg, as.numeric(factor(sample(c("a", "b", "c", "d"), nrow(mtcars), T))), data=mtcars, facets = vs ~ am) + 
    geom_hline(aes(yintercept = as.numeric(z)), hline.data) 

但我失去了期望因子標籤。

回答

2

一個解決方法是添加z的數字版本,而不是它

hline.data <- data.frame(z = factor(c("a", "b", "c", "d")), vs = c(0,0,1,1), 
         am = c(0,1,0,1)) 

## add numeric version of `z` as a new variable 
hline.data <- transform(hline.data, z0 = as.numeric(z)) 

p <- qplot(mpg, factor(sample(c("a", "b", "c", "d"), nrow(mtcars), T)), 
      data=mtcars, facets = vs ~ am) 
p + geom_hline(aes(yintercept = z0), hline.data) 

轉換生產

enter image description here

+0

這工作,但感覺就像一個黑客攻擊。這是ggplot2中的錯誤還是可能在其GitHub網站上要求的東西? –

+0

@TylerRinker很難判斷它是否是一個錯誤,因爲文檔沒有說明'yintercept'接受了什麼。沒有合理的座標系統,其中一個字符因素是有意義的。儘管y軸被標記了字符,但y軸的數字縮放。 –

+0

確實如此,但這在某種程度上類似於點圖行爲。我希望這種行爲能夠在此延伸。我把它作爲ggplot郵件列表的後續工作。 –