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

如何使用geom\u text position\u堆栈作为其aes的一部分?

  •  1
  • SkyWalker  · 技术社区  · 7 年前

    我有以下数据框:

    df <- data.frame(x=c(1,2,3,4,5),
                     y=c(2,3,5,9,9),
                     label=c('blah1','blah2','blah3','blah4','blah5'),
                     vjust=c('top','bottom','top','bottom','top'),
                     posVjust=c(0.9,1.1,0.9,1.1,0.9),
                     stringsAsFactors=FALSE)
    

    可以这样直接绘制:

    p <- ggplot(df, aes(x=x,y=y,label=label)) + geom_point() + geom_line() +
             geom_text(aes(vjust=vjust))
    p
    

    但是,我想使用 posVjust 列作为的一部分 geom_text aes 但我不喜欢这样:

    geom_text(aes(vjust=vjust,position=position_stack(vjust=posVjust))) 
    

    我得到以下错误:

    Warning: Ignoring unknown aesthetics: position
    > p
    Don't know how to automatically pick scale for object of type     
    PositionStack/Position/ggproto. Defaulting to continuous.
    Error: Aesthetics must be either length 1 or the same as the data (5): vjust,   
      position, x, y, label
    

    有没有办法使用我的 posVjust公司 列作为 position_stack 呼叫

    1 回复  |  直到 7 年前
        1
  •  1
  •   eipi10    7 年前

    position 不是一种审美观 aes . 据我所知, position_stack 获取单个值,而不是向量。但是,您可以更改 posVjust 成为 posVjust=c(-0.1,0.1,-0.1,0.1,-0.1) 然后执行以下操作:

    ggplot(df, aes(x=x, y=y,label=label)) + geom_point() + geom_line() +
      geom_text(aes(y=y + posVjust))
    

    你也可以省去 posVjust公司 只要做到:

    ggplot(df, aes(x=x, y=y,label=label)) + geom_point() + geom_line() +
      geom_text(aes(y=y + c(-0.1,0.1)))
    

    您可以添加 vjust=vjust 同样,这将增加一个小的额外垂直偏移增量。

    另一种选择是删除点,只使用标签而不是点标记。抵消 geom_text 然后标签就变得不必要了。例如:

    ggplot(df, aes(x=x, y=y, label=label)) + 
      geom_line(linetype="12", colour="grey50") +
      geom_text() +
      theme_bw()