Animated sorted bar chart with bars overtaking each other

后端 未结 3 549
傲寒
傲寒 2020-11-29 16:05

Edit: keyword is \'bar chart race\'

How would you go at reproducing this chart from Jaime Albella in R ?

See the animation on visualcapitalist.com o

3条回答
  •  借酒劲吻你
    2020-11-29 17:08

    This is what I came up with, so far, based in good part on @Jon's answer.

    p <- gdp  %>%
      # build rank, labels and relative values
      group_by(Year) %>%
      mutate(Rank = rank(-Value),
             Value_rel = Value/Value[Rank==1],
             Value_lbl = paste0(" ",round(Value/1e9)))  %>%
      group_by(Country.Name) %>%
      # keep top 10
      filter(Rank <= 10) %>%
      # plot
      ggplot(aes(-Rank,Value_rel, fill = Country.Name)) +
      geom_col(width = 0.8, position="identity") +
      coord_flip() + 
      geom_text(aes(-Rank,y=0,label = Country.Name,hjust=0)) +       #country label
      geom_text(aes(-Rank,y=Value_rel,label = Value_lbl, hjust=0)) + # value label
      theme_minimal() +
      theme(legend.position = "none",axis.title = element_blank()) +
      # animate along Year
      transition_states(Year,4,1)
    
    animate(p, 100, fps = 25, duration = 20, width = 800, height = 600)
    

    I might come back to improve it.

    The moving grid could be simulated by removing the actual grid and having geom_segment lines moving and fading out thanks to an alpha parameter changing when it approaches 100 billion.

    To have labels changing values between years (which gives a nice feeling of urgency in the original chart) I think we have no choice but multiplying the rows while interpolating labels, we'll need to interpolate Rank too.

    Then with a few minor cosmetic changes we should be pretty close.

提交回复
热议问题