如果我的 y 变量有一个因子并尝试在其中使用geom_hline
,facet_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)
但我失去了所需的因素标签。