代码之家  ›  专栏  ›  技术社区  ›  moodymudskipper

`使用`ggplot2::stat时未找到y``

  •  2
  • moodymudskipper  · 技术社区  · 6 年前

    假设我想用以下数据绘制一个条形图:

    df <- aggregate(Sepal.Length ~ Species, iris, mean)
    #      Species Sepal.Length
    # 1     setosa        5.006
    # 2 versicolor        5.936
    # 3  virginica        6.588
    
    p <- ggplot(df, aes(Species, Sepal.Length)) + geom_col()
    
    layer_data(p)
    #   x     y PANEL group ymin  ymax xmin xmax colour   fill size linetype alpha
    # 1 1 5.006     1     1    0 5.006 0.55 1.45     NA grey35  0.5        1    NA
    # 2 2 5.936     1     2    0 5.936 1.55 2.45     NA grey35  0.5        1    NA
    # 3 3 6.588     1     3    0 6.588 2.55 3.45     NA grey35  0.5        1    NA
    

    我想在中等高度的吧台上添加标签,这很有效:

    p + geom_text(aes(y=Sepal.Length/2, label = Species), color="white")
    

    但我不想重复 Sepal.Length ,所以我尝试使用 stat 但我有一个错误:

    p + geom_text(aes(y=stat(y)/2, label = Species), color="white")
    

    乐趣中的错误(X[[i]],…):找不到对象“y”

    这很奇怪,因为有些变量来自 layer_data(p) 在其他人不起作用的情况下起作用,例如:

    p + geom_text(aes(y=stat(x)/2, label = Species), color="white")
    p + geom_text(aes(y=stat(group)/2, label = Species), color="white")
    

    这也会起作用:

    p <- ggplot(df, aes(Species, Sepal.Length, yy =Sepal.Length)) + geom_col()
    p + geom_text(aes(y=stat(yy)/2, label = Species), color="white")
    

    这是虫子吗?我怎样才能解决这个问题?

    我的配置(在windows上):

    R.Version()$version.string
    # [1] "R version 3.3.1 (2016-06-21)"
    .rs.rVersionString()
    # [1] "3.3.1"
    packageVersion("ggplot2")
    # [1] ‘3.0.0’
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   moodymudskipper    6 年前

    我不确定它有多强大,但似乎 x , y PANEL 可通过 .data 代词

    它们是以它们的原始名称和原始价值命名的,而不是来自 layer_data ,所以如果我不想重复 Sepal.Length Species 我能做到:

    p + geom_text(aes(
      y     = .data[[names(.data)[2]]]/2,
      label = .data[[names(.data)[1]]]),
      color = "white")