To pass specifications, you need to complete all questions, especially the final couple questions. You should have a functional animation with a working “play” button and some customized options. The animated line document on Canvas may be useful as another reference for animations using Plotly in R.

Note the use of the p_load() function from the pacman package!

knitr::opts_chunk$set(
    echo = TRUE,
    message = FALSE,
    warning = FALSE,
    comment=NA
)
pacman::p_load(plotly, gapminder, dplyr)

Q1

Load the gapminder dataset into your R environment and take a look at it. Note the location of different variables and include a summary of the average and maximum GDP by continent.

# Load gapminder dataset
data("gapminder")

# Display the structure of the gapminder dataset
str(gapminder)
tibble [1,704 × 6] (S3: tbl_df/tbl/data.frame)
 $ country  : Factor w/ 142 levels "Afghanistan",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ continent: Factor w/ 5 levels "Africa","Americas",..: 3 3 3 3 3 3 3 3 3 3 ...
 $ year     : int [1:1704] 1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 ...
 $ lifeExp  : num [1:1704] 28.8 30.3 32 34 36.1 ...
 $ pop      : int [1:1704] 8425333 9240934 10267083 11537966 13079460 14880372 12881816 13867957 16317921 22227415 ...
 $ gdpPercap: num [1:1704] 779 821 853 836 740 ...
# Calculate average and maximum GDP by continent
gapminder_summary <- gapminder %>%
  group_by(continent) %>%
  summarize(
    avg_gdpPercap = mean(gdpPercap, na.rm = TRUE),
    max_gdpPercap = max(gdpPercap, na.rm = TRUE)
  )

# Display the summary
print(gapminder_summary)
# A tibble: 5 × 3
  continent avg_gdpPercap max_gdpPercap
  <fct>             <dbl>         <dbl>
1 Africa            2194.        21951.
2 Americas          7136.        42952.
3 Asia              7902.       113523.
4 Europe           14469.        49357.
5 Oceania          18622.        34435.

Q2

Using plotly, create a static bubble chart of the gapminder data. Map GDP to the x axis, life expectancy to the Y axis, and population to the size of the bubbles. Each bubble’s color should be based on the region of that nation. Hint: If size is not working properly for you, you may want to use: marker = list(sizemode = "diameter"))

#Uncomment and modify the line below this one to create your plot!
#static_plot <- plot_ly(...)

# Create a static bubble chart with plotly
static_plot <- plot_ly(
  data = gapminder,
  x = ~gdpPercap,
  y = ~lifeExp,
  size = ~pop,
  color = ~continent,
  type = 'scatter',
  mode = 'markers',
  marker = list(sizemode = "diameter")
) %>%
  layout(
    title = "Gapminder Bubble Chart: GDP vs Life Expectancy",
    xaxis = list(title = "GDP per Capita"),
    yaxis = list(title = "Life Expectancy"),
    showlegend = TRUE
  )
static_plot

Note here that the plot looks pretty messy because all the years are present on the plot. It would be nice to see the dots by country one year at a time, right?

Q3

Create a new plotly object that is similar to the previous one, but includes animation. This is as easy as adding frame to your plot_ly command and specifying the varable that should determine the frame.

# Create an animated bubble chart with plotly
animated_plot <- plot_ly(
  data = gapminder,
  x = ~gdpPercap,
  y = ~lifeExp,
  size = ~pop,
  color = ~continent,
  frame = ~year,
  type = 'scatter',
  mode = 'markers',
  marker = list(sizemode = "diameter")
) %>%
  layout(
    title = "Gapminder Animated Bubble Chart: GDP vs Life Expectancy Over Time",
    xaxis = list(title = "GDP per Capita", type = "log"),
    yaxis = list(title = "Life Expectancy"),
    showlegend = TRUE
  )

# Display the animated plot
animated_plot

Q4

Try adding a few options to alter your animation lightly. As long as you’ve created your plot correctly, all you need to do here is uncomment the code, run the chunk, and explain what each part did.

#Uncomment the lines below to see the updated animation. 
#animated_chart <- animated_plot %>% 
#  animation_opts(frame = 100,  #What did this do?
#                 redraw = TRUE, # What did this do?
#                 easing = "linear", #What did this do?
#                 autoplay = TRUE #What did this do)
#animated_chart

# Uncomment and modify code to add animation options
animated_chart <- animated_plot %>% 
  animation_opts(
    frame = 100,        # Duration of each frame in milliseconds
    redraw = TRUE,      # Forces a redraw on each frame for smoother transitions
    easing = "linear",  # Maintains a constant animation speed
    #autoplay = TRUE     # Automatically starts the animation when the plot loads, so users don’t need to click play manually.
  )

# Display the updated animated chart
animated_chart

Q5

Now, let’s add a button to pause the animation. You should spend a bit of time looking at this code and understanding what it does, then try to move the button to a place that makes more sense.

# interactive_chart <- animated_chart %>% layout(
#   updatemenus = list(
#     list(
#       type = "buttons",
#       showactive = FALSE,
#       x = 0,  
#       y = 0,  
#       buttons = list(
#         
#         list(
#           label = "Pause",
#           method = "animate",
#           args = list(NULL, list(frame = list(duration = 0, 
#                                               redraw = TRUE), 
#                                  mode = "immediate"))
#         )
#       )
#     )
#   )
# )
# interactive_chart

# Enhanced animated chart with Play and Pause buttons
interactive_chart <- animated_chart %>% 
  layout(
    updatemenus = list(
      list(
        type = "buttons",
        showactive = FALSE,         # Keeps buttons inactive when not in use
        x = -0.05,                    # Center horizontally below the chart
        y = -0.08,                   # Position below the plot
        xanchor = "center",         # Anchor the buttons at the center
        yanchor = "top",            # Anchor the buttons above the set y position
        buttons = list(
          list(
            label = "Pause",
            method = "animate",
            args = list(NULL, list(
              frame = list(duration = 0, redraw = TRUE),
              mode = "immediate"
            ))
          )
        )
      )
    )
  )

# Display the chart with Play and Pause buttons
interactive_chart

Q6

Add a title, axis labels, any other important annotations to the plot. This could include adding hover text or other elements.

# Enhanced animated chart with titles, axis labels, and hover text
interactive_chart <- animated_chart %>%
  layout(
    title = "Global Development Trends Over Time",
    xaxis = list(
      title = "GDP per Capita (log scale)",
      type = "log",
      tickangle = 45
    ),
    yaxis = list(
      title = "Life Expectancy (years)"
    ),
    updatemenus = list(
      list(
        type = "buttons",
        showactive = FALSE,         # Keeps buttons inactive when not in use
        x = -0.05,                    # Center horizontally below the chart
        y = -0.08,                   # Position below the plot
        xanchor = "center",         # Anchor the buttons at the center
        yanchor = "top",            # Anchor the buttons above the set y position
        buttons = list(
          list(
            label = "Pause",
            method = "animate",
            args = list(NULL, list(
              frame = list(duration = 0, redraw = TRUE),
              mode = "immediate"
            ))
          )
        )
      )
    ),
    annotations = list(
      list(
        text = "Source: Gapminder Dataset",
        x = 1,
        y = -0.4,
        showarrow = FALSE,
        xref = "paper",
        yref = "paper",
        xanchor = "right",
        yanchor = "auto",
        xshift = 0,
        yshift = 0,
        font = list(size = 12, color = "grey")
      )
    )
  ) %>%
  style(
    hoverinfo = "text",
    text = ~paste(
      "Country:", gapminder$country, "<br>",
      "Continent:", gapminder$continent, "<br>",
      "Year:", gapminder$year, "<br>",
      "GDP per Capita:", round(gapminder$gdpPercap, 2), "<br>",
      "Life Expectancy:", round(gapminder$lifeExp, 1), "<br>",
      "Population:", scales::comma(gapminder$pop)
    )
  )

# Display the enhanced interactive chart
interactive_chart

Q7

Practice publishing your final plot to Rpubs (or another location of your choice) and include the link in your submission.