【发布时间】:2018-05-23 14:54:43
【问题描述】:
我正在尝试开发一个使用 ggplot 的函数,但我遇到了 aes() 函数和我将传递给 geom_point() 的参数的问题,特别是 color 和 shape。
这是一个非常简化的代码版本,它开始出现问题。了解代码试图实现的目标的一些背景可能会有所帮助。假设我们有带有变量 Dose 和 Response 的数据框 x,并且有一个名为 OutlierDetect(Dose,Response) 的函数返回 x 的索引,这似乎是某个拟合曲线的异常值。目标是将这些索引绘制成与其余数据不同的形状。
a <- ggplot(NULL, aes(x = Dose, y = Response)
shape.vec <- rep(19, nrow(x))
out.index <- OutlierDetect(Dose=x$Dose,Response=x$Response)
shape.vec[out.index] <- 17
a <- a + geom_point(data = x, size = 5, alpha = 0.8, aes(color = "group1"), shape = shape.vec)
我想避免在 x 中放置一个因子列这一看似显而易见的答案,因为如果可能的话,我不想修改 x。并且代码是这样写的,所以它足够灵活,可以添加一组新的数据 y,以便将它们绘制在同一个图上,并且 ggplot 会自动生成颜色图例。
我收到错误Error: Aesthetics must be either length 1 or the same as the data (1): shape, size, alpha。在我自己的研究中,制作图例时似乎是 ggplot 中的一个错误。出于某种原因,这两个参数需要具有相同的长度才能正常工作(参见下面的代码块)。
供参考,此代码块工作正常。
a <- ggplot(NULL, aes(x = Dose, y = Response)
shape.vec <- rep(19, nrow(x))
color.vec <- rep("blue", nrow(x)) #Need to manually specify new colors/color pallete which is more user input
out.index <- OutlierDetect(Dose=x$Dose,Response=x$Response)
shape.vec[out.index] <- 17
a <- a + geom_point(data = x, size = 5, alpha = 0.8, color = color.vec, shape = shape.vec)
这个块也是如此
a <- ggplot(NULL, aes(x = Dose, y = Response)
a <- a + geom_point(data = x, size = 5, alpha = 0.8, aes(color = "group1"), shape = 19)
# can add more data frames y, z, ect, so long
# as the aes color parameter has a different name
总之,我想要的是这两个代码块的混合。有什么建议么?
可重现的示例代码
x <- data.frame(Dose = c(1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10),
Response = seq(20))
a <- ggplot(NULL, aes(x = Dose, y = Response))
shape.vec <- rep(19, nrow(x))
out.index <- nrow(x) # lets say the OutlierDetect function always says the last index is an outlier
shape.vec[out.index] <- 17
a <- a + geom_point(data = x, size = 5, alpha = 0.8, aes(color = "group1"), shape = shape.vec)
【问题讨论】:
-
寻求帮助时,您应该包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出。但是,当您想在
aes()中使用的所有内容都来自数据源时,ggplot效果最好。您不必更改x,只需将一个版本传递给ggplot,其中包含绘图所需的所有列。 -
您可以使用
dput()来显示您的数据吗?如果不看您的数据是什么样子,就很难回答。见How to make a great R reproducible example -
你好 MrFlick,为了简单起见,
Dose <- c(1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10)和Response <- seq(20)假设最后一个索引被认为是异常值,即shape.vec[20] <- 17(实际数字无关紧要,错误出现在情节)但你是对的。我可以保存 x 的副本并对其进行修改,然后添加颜色变量和形状变量。这也应该有效。不过,我认为我最初的错误有点不直观。 -
@JustinLandis 所有这些代码都应该编辑到您的问题中,而不是放在评论中