gpt4 book ai didi

r - ggplot 2's aes_string() does not like "rownames(mtcars)"在函数内部时

转载 作者:行者123 更新时间:2023-12-04 10:36:53 27 4
gpt4 key购买 nike

我需要在函数内部生成一个图,依赖于 aes_string() ,我需要标签作为行名。

下面的情节工作正常,但 不在函数内 .

library(ggplot2)
data(mtcars)
plotfun <- function(cars) {
g <- ggplot(data = cars, aes_string(x = "mpg", y = "disp", label = "rownames(cars)"))
g <- g + geom_point()
g <- g + geom_text()
g
}
plotfun(cars = mtcars)

当作为函数运行时,这让我:
Error: Aesthetics must either be length one, or the same length as the dataProblems:mpg, disp

我无法绕过它。
我知道有很多 similar questions关于 aes_string()在函数内部——我只是无法根据我的问题调整他们的解决方案。

Ps.:显然,上面的MWE很愚蠢;在我的实际用例中,我通过 for 循环运行绘图,因此需要 aes_string() .

最佳答案

我认为 aes_q 会更好地为您服务在这里而不是 aes_string

library(ggplot2)
data(mtcars)
plotfun <- function(cars) {
g <- ggplot(data = cars, aes_q(x = as.name("mpg"), y = as.name("disp"), label=rownames(cars)))
g <- g + geom_point()
g <- g + geom_text()
g
}
plotfun(cars = mtcars)
aes_q允许您传递未评估的符号和调用,所以我们只使用 as.name()将您的字符串转换为稍后可以在您的数据中评估的符号。

关于r - ggplot 2's aes_string() does not like "rownames(mtcars)"在函数内部时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31484543/

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