代码之家  ›  专栏  ›  技术社区  ›  Justin Landis

r ggplot错误:美感长度匹配颜色和形状

  •  0
  • Justin Landis  · 技术社区  · 8 年前

    我试图开发一个使用ggplot的函数,但遇到了 aes() geom_point() ,具体来说, color shape .

    这是一个非常简单的代码版本,在这里事情开始打破。了解代码所要实现的目标的一些背景知识可能会有帮助。假设我们有一个数据框x,其中包含变量Dose和Response,并且有一个名为 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中放置一个factor列,因为如果可能的话,我不想修改x。代码是这样写的,所以它足够灵活,可以添加一组新的数据y,这样它们就被绘制在同一个图形上,ggplot会自动生成颜色图例。

    我收到错误信息 Error: Aesthetics must be either length 1 or the same as the data (1): shape, size, alpha

    作为参考,此代码块工作正常。

    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)
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   GordonShumway    8 年前

    你的代码有 nrow(x$Dose) nrow(x) length(x$Dose)

    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)
    

    enter image description here

    推荐文章