如果我的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)
但我失去了所需的因素标签。
答案 0 :(得分: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)
产