library(tidyverse)
library(p8105.datasets)
library(plotly)
data("instacart")

Bar plot showing total orders per aisle or department

#total numbers of orders per aisle
instacart |> 
  sample_n(10000) |> 
  count(department) |> 
  mutate(department = fct_reorder(department,n)) |> 
  plot_ly(
    x = ~department, y = ~n, 
    color = ~department, 
    type = "bar", 
    colors = "magma",
    text = ~paste("Orders:", n),
    hoverinfo = "text",
    textposition = "none"
  ) |> 
  layout(
    title = "Total Orders by Department",
    xaxis = list(title = "Department", tickangle = -45),
    yaxis = list(title = "Number of Orders")
  )

Scatter plot showing order hour of day vs. number of products in order

#sampling subset of users
sample_users = instacart |> 
  distinct(user_id) |> 
  sample_n(9000)

sample_data = instacart |> 
  semi_join(sample_users, by = "user_id")
  
sample_data |> 
  group_by(order_id, order_hour_of_day) |> 
  count(order_id) |> 
  plot_ly(
    x = ~order_hour_of_day,
    y = ~n,
    color = ~order_hour_of_day,
    type = "scatter",
    mode = "markers",
    marker = list(opacity = 0.4),
    colors = "viridis"
  ) |> 
  layout(
    title = "Order Size vs. Time of Day",
    xaxis = list(title = "Hour of Day"),
    yaxis = list(title = "Number of Products per Order")
  )

Boxplot showing “add to cart” order vs. reorder status

sample_data |> 
  plot_ly(
    x = ~factor(reordered), y = ~add_to_cart_order, color = ~factor(reordered),
    type = "box",
    showlegend = FALSE,
    hoverinfo = "y",
    name = " ",
    showlegend = FALSE,
    colors = c("navy","darkred"),
    marker = list(opacity = 0.4)
  ) |> 
  layout(
    title = "Cart Position by Reorder Status",
    xaxis = list(title = "Item Type",
                 tickvals = c(0,1),
                 ticktext = c("New", "Reordered")
                 ),
    yaxis = list(title = "Item Added to Cart (Order)")
  )