gpt4 book ai didi

r - 水平线; y 轴作为因子 : ggplot2

转载 作者:行者123 更新时间:2023-12-04 02:56:43 26 4
gpt4 key购买 nike

如果我的 y 变量有一个因子,并尝试在 facet_grid 中使用 geom_hline,我会得到一个错误:

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)

但我丢失了所需的因子标签。

最佳答案

一个修复方法是添加一个数字版本的 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

关于r - 水平线; y 轴作为因子 : ggplot2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16551388/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com