1/1/2024

Overview

In these slides, I will load, manipulate, and plot data to show the number of visitors to each of California’s National Parks for each year from 2009 to 2018.

Data for this assignment was obtained from from the US National Park Service Visitor Use Statistics service.

Load the data

First, I load the visitor data using the fread() function from the data.table package.

data <- fread('park_data.csv', header = TRUE)
head(data, 5)
##               park    2009    2010    2011    2012    2013    2014    2015
## 1: Channel Islands  348745  277515  242756  249594  212029  342161  324816
## 2:    Death Valley  828574  984775  946867  984568  951972 1101312 1154843
## 3:     Joshua Tree 1304471 1434976 1396237 1396117 1383340 1589904 2025756
## 4:    Kings Canyon  609296  598205  566810  591033  567544  502268  468106
## 5: Lassen Volcanic  365639  384570  351269  407653  427409  432977  468092
##       2016    2017    2018
## 1:  364807  383687  366250
## 2: 1296283 1294827 1678660
## 3: 2505286 2853619 2942382
## 4:  607479  692932  699023
## 5:  536068  507256  499435

Tidy the data

I would like to convert the data from wide to long format to thereby display the data with two variables, year and visitors. I do this below using the gather() function from the tidyr package.

data <- data %>%
  gather(key = year, value = visitors, -park) %>%
  mutate(park = as.factor(park),
         year = as.factor(year))
head(data, 3)
##              park year visitors
## 1 Channel Islands 2009   348745
## 2    Death Valley 2009   828574
## 3     Joshua Tree 2009  1304471

Plot visitors by year using plotly

Next, I will plot the number of visitors (y) by year (x) as a line plot, with separate lines for each park.

I will use the plot_ly() function within the plotly package for added interactivity. Find the final plot on the next page.

plot_ly(data = data, x = ~year, y = ~visitors, type = "scatter", 
        mode = "lines", color = ~park)

CA national park visitors by year

Plot a subset of the data using ggplotly

Next, I will demonstrate the use of the ggplotly() function which converts a ggplot object to a plotly object.

I include code below that creates a ggplot object showing the number of visitors in each year from 2009-2018 for three of the lesser-visited parks, Channel Islands, Pinnacles, and Redwoods.

parksToKeep <- c('Channel Islands', 'Pinnacles', 'Redwoods')
p <- ggplot(data = data %>% 
              filter(park %in% parksToKeep),
            aes(x = year, y = visitors, colour = park)) +
  geom_point(size = 2) + geom_path(aes(group = park), size = 1) +
  scale_color_brewer(palette = "Accent") + 
  theme_minimal()

I then convert the ggpplot object to a plotly object:

ggplotly(p)