3

如果我的 y 变量有一个因子并尝试在其中使用geom_hlinefacet_grid则会出现错误:

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)

但我失去了所需的因素标签。

4

1 回答 1

4

A 修复是添加 的数字版本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)

生产

在此处输入图像描述

于 2013-05-14T19:51:30.597 回答