2013-05-14 64 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邮件列表的后续工作。 –