代码之家  ›  专栏  ›  技术社区  ›  Joachim Schork

gganimate round值在过渡期间

  •  0
  • Joachim Schork  · 技术社区  · 7 年前

    我想用gganimate包创建一个动画条形图。在每个条的顶部,我希望将该条的值舍入为零位。

    考虑以下示例:

    # Example data
    df <- data.frame(ordering = c(rep(1:3, 2), 3:1, rep(1:3, 2)),
                     year = factor(sort(rep(2001:2005, 3))),
                     value = round(runif(15, 0, 100)),
                     group = rep(letters[1:3], 5))
    
    # Create animated ggplot
    ggp <- ggplot(df, aes(x = ordering, y = value)) +
      geom_bar(stat = "identity", aes(fill = group)) +
      transition_states(year, transition_length = 2, state_length = 0) +
      geom_text(y = df$value, label = as.integer(round(df$value)))
    ggp
    

    enter image description here

    1 回复  |  直到 7 年前
        1
  •  4
  •   Mike N.    7 年前

    由于df$value已经通过round()四舍五入为零位小数,因此可以使用作为角色()设置标签时。

    > df$value
    [1] 29 81 92 50 43 73 40 41 69 15 11 66  4 69 78
    > as.character(df$value)
    [1] "29" "81" "92" "50" "43" "73" "40" "41" "69" "15" "11" "66" "4"  "69" "78"
    

    ggp <- ggplot(df, aes(x = ordering, y = value)) +
      geom_bar(stat = "identity", aes(fill = group)) +
      transition_states(year, transition_length = 2, state_length = 0) +
      geom_text(label = as.character(df$value))
    

    enter image description here

    推荐文章