24 Januar 2018

Agenda

This is an R Markdown presentation showcasing interactive plots with the package plotly.

  • Basic Charts
  • Countour and 3D Plots
  • Maps
  • Advanced Interactivity

Basic Charts: Code

legendtitle <- list(yref = "paper", xref = "paper", x = 1, y = 0.97, align = "left",
                    text="Number of\ncylinders", showarrow = FALSE)
mtcars %>% plot_ly(x = ~wt, y = ~mpg, color = ~factor(cyl),
                   size = ~hp, sizes = c(10,500)) %>%
  add_markers(hoverinfo = "text",
              text = ~paste("Weight: ", wt,
                            "\nMileage:", mpg,
                            "\nCylinders:", cyl,
                            "\nGRoss horsepower:", hp)) %>%
  layout(title = "mtcars: wt vs. mpg (color: cyl, size: hp)",
         annotations = legendtitle,
         legend = list(x = 0.88, y = 0.89),
         xaxis = list(title = "Weight (1000 lbs)"),
         yaxis = list(title = "Miles/(US) gallon"))

Basic Charts: Output

Contour and 3D Plots: Code

plot_ly(z = ~volcano, type = "contour")
plot_ly(z = ~volcano, type = "surface")

Contour and 3D Plots: Output (1)

Contour and 3D Plots: Output (2)

Maps: Code

str(state.abb)
str(state.x77)
state_pop <- as_tibble(data.frame(State = state.abb, Pop = as.vector(state.x77[, 1])))
state_pop$hover <- with(state_pop, paste(State, '<br>', "Population:", Pop))
state_pop
borders <- list(color = toRGB("black"))
map_options <- list(
  scope = 'usa',
  projection = list(type = 'albers usa'),
  showlakes = TRUE,
  lakecolor = toRGB('grey'))
state_pop %>% plot_ly(z = ~Pop, text = ~hover, locations = ~State, 
        type = 'choropleth', locationmode = 'USA-states', 
        color = ~Pop, colors = 'Reds', marker = list(line = borders)) %>%
  layout(title = 'US Population in 1975', geo = map_options)

Maps: Output

Advanced Interactivity: Code

x <- seq(-2 * pi, 2 * pi, length.out = 1000)
df <- data.frame(x, y1 = sin(x), y2 = cos(x))
plot_ly(df, x = ~x) %>% add_lines(y = ~y1, name = "A") %>%
  add_lines(y = ~y2, name = "B", visible = F) %>% layout(
    title = "Drop down menus - Styling",
    xaxis = list(domain = c(0.1, 1)),
    yaxis = list(title = "y"),
    updatemenus = list(
      list(y = 0.8,
           buttons = list(list(method = "restyle", label = "Blue",
                               args = list("line.color", "blue")),
                          list(method = "restyle", label = "Red",
                               args = list("line.color", "red")))),
      list(y = 0.7,
           buttons = list(list(method = "restyle", label = "Sin",
                               args = list("visible", list(TRUE, FALSE))),
                          list(method = "restyle", label = "Cos",
                               args = list("visible", list(FALSE, TRUE)))))))

Advanced Interactivity: Output