library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.1 ──
## ✓ ggplot2 3.3.5     ✓ purrr   0.3.4
## ✓ tibble  3.1.5     ✓ dplyr   1.0.7
## ✓ tidyr   1.1.3     ✓ stringr 1.4.0
## ✓ readr   2.0.1     ✓ forcats 0.5.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(p8105.datasets)
library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout

Examples with Plotly

We’re going to look at the Instacart dataset and graph a scatterplot, line graph and bar graph. Plotly was used to produce the graphs below as well as the ones produced in the dashboard.

Scatterplot

instacart %>%
  count(aisle) %>%
  plot_ly(x = ~aisle, y = ~n, color = ~aisle, type = "scatter")
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode
## Warning in RColorBrewer::brewer.pal(N, "Set2"): n too large, allowed maximum for palette Set2 is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(N, "Set2"): n too large, allowed maximum for palette Set2 is 8
## Returning the palette you asked for with that many colors

Line graph

instacart %>% 
  sample_n(10) %>%
  group_by(product_name, order_dow) %>% 
  summarize(mean = mean(order_hour_of_day)) %>% 
  plot_ly(y = ~mean, x = ~product_name, type = "scatter", mode = "line")
## `summarise()` has grouped output by 'product_name'. You can override using the `.groups` argument.

Bar chart

instacart %>% 
  count(department) %>% 
  mutate(department = fct_reorder(department, n)) %>% 
  plot_ly(x = ~department, y = ~n, color = ~department, type = "bar", colors = "viridis")