gpt4 book ai didi

r - 使用 ggplot aes_string、组和线型时出现的问题

转载 作者:行者123 更新时间:2023-12-01 11:41:56 24 4
gpt4 key购买 nike

假设我有这个数据集:

x <- rnorm(1000)
y <- rnorm(1000, 2, 5)
line.color <- sample(rep(1:4, 250))
line.type <- as.factor(sample(rep(1:5, 200)))

data <- data.frame(x, y, line.color, line.type)

我试图通过 line.type 和 line.color 的相互作用绘制 x 和 y 变量组。此外,我想使用 line.type 指定线型,​​使用 line.color 指定颜色。如果我这样写:

ggplot(data, aes(x = x, y = y, group = interaction(line.type, line.color), colour = line.color, linetype = line.type)) + geom_line()

它有效,但如果我尝试像这样使用 aes_string:

interact <- c("line.color", "line.type")
inter <- paste0("interaction(", paste0('"', interact, '"', collapse = ", "), ")")

ggplot(data, aes_string(x = "x", y = "y", group = inter, colour = "line.color", linetype = "line.type")) + geom_line()

我得到错误:

Error: geom_path: If you are using dotted or dashed lines, colour, size and linetype must be constant over the line

我做错了什么?我需要使用 aes_string,因为我有很多变量要绘制。

最佳答案

原来我在上面的评论中有几个地方是错误的。这似乎有效:

data$inter <- interaction(data$line.type,data$line.color)
ggplot(data, aes_string(x = "x", y = "y", group = "inter",colour = "line.color",linetype = "line.type")) + geom_line()

(关于在单条虚线/点线内指定不同颜色等的图表,我完全错了。)

不过,我认为这是一个轻微的证明,即依赖于解析 aes_string() 中的 interaction 代码通常不是一个好主意。我的猜测是 ggplot 在复杂情况下尝试解析您提供的 aes_string() 的尝试中存在一个小错误,这导致它按顺序评估事物,使其看起来像要求通过虚线/点线改变美学。

关于r - 使用 ggplot aes_string、组和线型时出现的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19410781/

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