---
title: "Simple Animated Plots"
date: today
toc: true
format:
  html: 
    code-overflow: wrap
    toc: true
    toc-title: "Contents"
    theme: solar
    # hide code?

execute:
  warning: false
  message: false
---

# Visual Global Climate Events & Economic Impact with Animations

As usual, we'll use the `tidyverse` but also some new packages that you will have to install. Uncomment the lines below if you don't already have them installed.

```{r, label=libraries}
library(tidyverse)
# install gifski and av
# install.packages("gifski")
# install.packages("av")
# install.packages("gganimate") 
library(gganimate)
```

Load [this](https://www.kaggle.com/datasets/uom190346a/global-climate-events-and-economic-impact-dataset) data from Kaggle. From the website - 

*This comprehensive dataset tracks major climate events worldwide and their economic impact from 2020 to September 2025. With over 3,000 documented events across 51 countries, this dataset provides crucial insights into the increasing frequency and severity of climate-related disasters and their economic consequences.*

```{r, label=read_in_gce}

gce <-read_csv("https://euclid.nmu.edu/~joshthom/teaching/dat309/week6/global_climate_events_economic_impact_2020_2025.csv")

glimpse(gce)
```

# An initial barplot

```{r}
ggplot(gce, aes(y = country, fill = country)) + 
  geom_bar() +
  theme(legend.position = "none")
```

# Reorder to improve the readability w/ lollipop plot

Read [here](https://r-graph-gallery.com/lollipop-plot.html) for more.

```{r}
events_per_country <- count(gce,country) |> 
  mutate(country = reorder(country,n))

events_per_country |> 
  ggplot(aes(y = country, x = n)) + 
  geom_segment(aes(x=0, xend=n, y=country, yend=country)) +
  geom_point(aes(color=country)) +
  theme_minimal() +
  theme(legend.position = "none")
```

# Repeat the plot but for just one year
```{r}
events_per_country <- filter(gce,year == 2020) |> 
  count(country) |> 
  mutate(country = reorder(country,n))

events_per_country |> 
  ggplot(aes(y = country, x = n)) + 
  geom_segment(aes(x=0, xend=n, y=country, yend=country)) +
  geom_point(aes(color=country)) +
  theme_minimal() +
  theme(legend.position = "none")
```

# Animate over a variable

```{r}
# count below is equivalent to: group_by() |> summarize(n=n())
events_per_country <- count(gce,country,year) |> 
  mutate(country = reorder(country,n))

events_per_country |> 
  ggplot(aes(y = country, x = n)) + 
  geom_segment(aes(x=0, xend=n, y=country, yend=country)) +
  geom_point(aes(color=country)) +
  theme_minimal() +
  theme(legend.position = "none") +
  # the animation steps
  transition_states(states=year, # year is a variable in data
                    transition_length = 1,
                    state_length = 10) +
  enter_fade() + 
  exit_fade() + 
  ease_aes('linear') + 
  labs(title = "Year: {closest_state}",  
       y = "Country", x = "Number of Events")

last_animation() # display the animation
```

# Exercise

1. Produce a similar animation, but animate over the economic impact, affected population or other variable.   

```{r,label=summarize}
economic_impact_per_event <- group_by(gce,event_type,year) |> 
  summarize(
    econ = sum(economic_impact_million_usd)) |>
    mutate(event_type = reorder(event_type,econ))
```

```{r, label=gce_ani}
p <- economic_impact_per_event |> 
  ggplot(aes(y = event_type, x = econ)) + 
  geom_segment(aes(x=0, xend=econ, y=event_type, yend=event_type)) +
  geom_point(aes(color=event_type)) +
  theme_minimal() +
  theme(legend.position = "none") +
  # the animation steps
  transition_states(states=year, # year is a variable in data
  ) +
  #                  transition_length = 1,
  #                  state_length = 10) +
  enter_fade() + 
  exit_fade() + 
  ease_aes('linear') + 
  labs(title = "Year: {closest_state}",  
       y = "Event Type", x = "Economic Impact in Millions of USD")

animate(p, 
        duration = 10, # 41 countries, 2 seconds each
        fps  =  5,
        #nframes = [...or pick it here])
)

```

# Using plotly to animate

## dataset CO2

In R's datasets:

*Atmospheric concentrations of CO2​are expressed in parts per million (ppm) and reported in the preliminary 1997 SIO manometric mole fraction scale.*

```{r}
a <- datasets::co2

# before you move on notice the structure of the data in a, it's not tidyverse friendly

# tidy the data
co2_tib <- data.frame(matrix(co2, ncol = 12, byrow = TRUE)) %>% 
  setNames(c('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug',
             'Sep','Oct','Nov','Dec')) %>%
  mutate(year = as.character(1959:1997))

# pivot to make plotting easy
co2_long <- co2_tib |> pivot_longer(cols = !year, names_to ="month", values_to="level")
```

## Use plotly

```{r}
library(plotly)

fig <- co2_long %>%
  plot_ly(
    x = ~month,
    y = ~level,
    frame = ~year,
    type = 'scatter',
    mode = 'markers',
    showlegend = F,
    size = 10
  ) |>
  layout(title = "Atmospheric Concentration of CO2")

fig
```

# Other forms of Interactivity

```{r}
    library(plotly)

    p <- gce %>%
    ggplot( aes(
      x = affected_population, 
      y = total_casualties, 
      size = infrastructure_damage_score, 
      color=event_type)) +
      scale_x_continuous(trans = "log") +
    geom_point() +
    theme_bw()

    ggplotly(p)
```

You can:

- Zoom by selecting an area of interest

- Hover the line to get exact time and value

- Export to png

- Slide axis

- Double click to re-initialize.

# 3-D Plots

The package `rgl` is great for 3D plots. It creates a stand-alone window of your 3d plot.

```{r, label=rgl}
# install.packages("rgl")
library(rgl)
# Data: the iris data is provided by R
data <- iris

# Add a new column with color
mycolors <- c('royalblue1', 'darkcyan', 'oldlace')
data <- mutate(data,color = mycolors[ as.numeric(Species) ])

# Plot
plot3d( 
  x=data$`Sepal.Length`, y=data$`Sepal.Width`, z=data$`Petal.Length`, 
  col = data$color, 
  type = 's', 
  radius = .1,
  xlab="Sepal Length", ylab="Sepal Width", zlab="Petal Length")
```

To display it in a Quarto/R Markdown document:

```{r, label = widget} 
# To display in an R Markdown document:
rglwidget()
```

## Exercise
Repeat the 3d plot above on the `penguins` data, or the `gce` data.  
