The Big Picture

Our primary focus in this section is on the Visualize phase.

Our primary focus in this section is on the Visualize phase.

Packages You will Need

library(mdsr)
library(babynames)
library(plotly)
library(bpexploder)
library(Lahman)
library(dygraphs)
library(glue)

bpexploder

The chickWts Data

?chickwts

Which type of feed produced the most growth?

We’ll investigate with package bpexploder:

library(bpexploder)

The Code

bpexploder(data = chickwts,
           settings = list(
             yVar = "weight",
             groupVar = "feed",
             levels = levels(with(chickwts,
                                  reorder(feed, weight, median))),
             levelLabels = NULL,
             levelColors = RColorBrewer::brewer.pal(6, "Set3"),
             yAxisLabel = "6-week weight (grams)",
             xAxisLabel = "type of feed",
             tipText = list(
               weight = "weight"),
             relativeWidth = 0.90,
             align = "center",
             # aspect = width/height, defaults to 1.25
             aspect = 1.5)
           )

The Plot

None! Sadly, they don’t show up in ioslides.

An htmlwidget

plotly

Top Home Run Hitters

HomeRunLeaders <-
  Batting %>% 
  filter(lgID %in% c("AL", "NL")) %>% 
  group_by(yearID) %>% 
  arrange(desc(HR)) %>% 
  filter(row_number() == 1) %>% 
  inner_join(Master, by = "playerID") %>% 
  mutate(name = paste(nameFirst, nameLast)) %>% 
  rename(season = yearID, team = teamID, league = lgID) %>% 
  select(name, team, season, HR, league)

Plot Them

library(plotly)
p <-
  ggplot(HomeRunLeaders, aes(x = season, y = HR)) +
    geom_line() +
    geom_point(aes(label = name, label1 = team)) +
    labs(x = NULL, y = "Home Runs")
ggplotly(p)

Customizing the Tooltip

HomeRunLeaders <-
  HomeRunLeaders %>% 
  mutate(tip = glue::glue(
    "Playing for {team} in {season}, 
    {name} hit {HR} home runs."
  ))
p <-
  ggplot(HomeRunLeaders, aes(x = season, y = HR)) +
    geom_line() +
    geom_point(aes(label = tip)) +
    labs(x = NULL, y = "Home Runs")
ggplotly(p, tooltip = "label") %>% 
  config(displayModeBar = FALSE)  ## get rid of tool-bar

Directly in plotly

HomeRunLeaders %>% 
  plot_ly(x = ~ season, y = ~ HR,
         text = ~ paste("Name: ", name, '<br>Team:', team),
         color = ~ league) %>% 
  config(displayModeBar = FALSE)

Learn More

dygraphs

The Beatles

Beatles <-
  babynames %>% 
  filter(name %in% c("John", "Paul", "George", "Ringo") & sex == "M") %>% 
  select(year, name, prop) %>% 
  tidyr::spread(key = name, value = prop, fill = 0)

Plot Their Popularity

Beatles %>% 
  dygraph(main = "Popularity of Beatle Names") %>% 
  dyRangeSelector(dateWindow = c("1940", "1980"))

Learn More