# Animated Choropleths

Animated choropleths are a useful way to understand how regional values change over time. Consider the US Presidential Election choropleth: it is normally used to show how each state voted in the last presidential election. But what if you want to understand how the results of last election compare to the previous election? Or the election before? In this case an animated choropleth is an effective tool to understand the data.

### Example: Historical US Presidential Election Results

choroplethr ships with an example dataset of all US Presidential Election returns. This data is in the variable `df_president_ts`.

    library(choroplethr)

    ?df_president_ts
    data(df_president_ts)

    head(df_president_ts, n=1)

    ##    region 1789 1792 1796 1800 1804 1808 1812 1816 1820    1824 1828 1832
    ## 1 alabama <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>   DR Jackson    D    D
    ##   1836 1840 1844 1848 1852 1856 1860 1864 1868 1872 1876 1880 1884 1888
    ## 1    D    D    D    D    D    D   SD <NA>    R    R    D    D    D    D
    ##   1892 1896 1900 1904 1908 1912 1916 1920 1924 1928 1932 1936 1940 1944
    ## 1    D    D    D    D    D    D    D    D    D    D    D    D    D    D
    ##   1948 1952 1956 1960 1964 1968 1972 1976 1980 1984 1988 1992 1996 2000
    ## 1   SR    D    D    I    R   AI    R    D    R    R    R    R    R    R
    ##   2004 2008 2012
    ## 1    R    R    R

### Animating the data

To animate this data.frame use the `choroplethr_animate` function (?choroplethr_animate). It has one argument, a list of choropleths. Our first task, then, is to convert `df_president_ts` into a list of choropleths:

    # create a list of choropleths of presidential election results for each year
    choropleths = list()
    for (i in 2:ncol(df_president_ts)) {
      df           = df_president_ts[, c(1, i)]
      colnames(df) = c("region", "value")
      title        = paste0("Presidential Election Results: ", colnames(df_president_ts)[i])
      choropleths[[i-1]] = state_choropleth(df, title=title)
    }

Then call choroplethr_animate with the list of choropleths:

    choroplethr_animate(choropleths)

### Output

choroplethr_animate will write each choropleth to your current working directory with the naming convention `choropleth_1.png`, `choropleth_2.png`, etc. It will then write an HTML file named `animated_choropleth.html`. Open that file with a browser - it contains a JavaScript based player that allows you to cycle thru all the images.

Here is a screenshot of the player. Note that in the upper right hand corner are play and stop buttons. Clicking them will play or stop the animation. There are also + and - buttons which allow you to cycle thru the animation at your own speed.