Animated sorted bar chart with bars overtaking each other

后端 未结 3 551
傲寒
傲寒 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:11

    This is what I came up, I just use Jon and Moody code as a template and make few changes.

    library(tidyverse)
    library(gganimate)
    library(gapminder)
    theme_set(theme_classic())
    
    gdp <- read.csv("https://raw.github.com/datasets/gdp/master/data/gdp.csv")
    words <- scan(
      text="world income only total dividend asia euro america africa oecd",
      what= character())
    pattern <- paste0("(",words,")",collapse="|")
    gdp  <- subset(gdp, !grepl(pattern, Country.Name , ignore.case = TRUE))
    colnames(gdp) <- gsub("Country.Name", "country", colnames(gdp))
    colnames(gdp) <- gsub("Country.Code", "code", colnames(gdp))
    colnames(gdp) <- gsub("Value", "value", colnames(gdp))
    colnames(gdp) <- gsub("Year", "year", colnames(gdp))
    
    gdp$value <- round(gdp$value/1e9)
    
    gap <- gdp %>%
      group_by(year) %>%
      # The * 1 makes it possible to have non-integer ranks while sliding
      mutate(rank = min_rank(-value) * 1,
             Value_rel = value/value[rank==1],
             Value_lbl = paste0(" ",value)) %>%
      filter(rank <=10) %>%
      ungroup()
    
    p <- ggplot(gap, aes(rank, group = country, 
                         fill = as.factor(country), color = as.factor(country))) +
      geom_tile(aes(y = value/2,
                    height = value,
                    width = 0.9), alpha = 0.8, color = NA) +
      geom_text(aes(y = 0, label = paste(country, " ")), vjust = 0.2, hjust = 1) +
      geom_text(aes(y=value,label = Value_lbl, hjust=0)) +
      coord_flip(clip = "off", expand = FALSE) +
      scale_y_continuous(labels = scales::comma) +
      scale_x_reverse() +
      guides(color = FALSE, fill = FALSE) +
    
      labs(title='{closest_state}', x = "", y = "GDP in billion USD",
           caption = "Sources: World Bank | Plot generated by Nitish K. Mishra @nitishimtech") +
      theme(plot.title = element_text(hjust = 0, size = 22),
            axis.ticks.y = element_blank(),  # These relate to the axes post-flip
            axis.text.y  = element_blank(),  # These relate to the axes post-flip
            plot.margin = margin(1,1,1,4, "cm")) +
    
      transition_states(year, transition_length = 4, state_length = 1) +
      ease_aes('cubic-in-out')
    
    animate(p, 200, fps = 10, duration = 40, width = 800, height = 600, renderer = gifski_renderer("gganim.gif"))
    

    GDP changes per year Here I am using duration 40 second, which is slow. You can change duration and make it faster or slower as you needed.

提交回复
热议问题