library(plotly)

library(dplyr)
library(tibble)
library(ggplot2)
## https://plotly.com/r/figure-structure/#figures-as-trees-of-attributes
# Attributes: 
# Data - listed by trace ~~ geoms
# Layout - title/legend/axes/tickmarks
# Frames - for animations

Annotate Points with mouseover labels

mtcarsdata <- mtcars %>% rownames_to_column(var="model")

plotly code

plot_ly(mtcarsdata, x= ~ mpg, y= ~ disp, 
        text=~model)

with ggplot syntax

carsplot <- mtcarsdata %>%
  ggplot(aes(x=mpg, y=disp, text=model))+
  geom_point(aes(fill=NA))

ggplotly(carsplot)
ggplotly(carsplot, tooltip=c("model"))

You can zoom in !!

library(gapminder)

p <- gapminder %>%
  ggplot(aes(x=year, y=pop, group=country, color=continent, text=lifeExp))+
  scale_y_continuous(transform="log")+
  geom_line()

ggplotly(p)
ggplotly(p, tooltip=c("country"))

can’t label with a column not referenced in ggplot.

ggplotly(p, tooltip=c("gdpPercap"))  #Doesn't work
ggplotly(p, tooltip=c("lifeExp"))  #Does work because lifeExp is in ggplot as text

Maps

https://plotly.com/r/#maps

library(rjson)
    
url <- 'https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json'
counties <- rjson::fromJSON(file=url)
url2<- "https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv"
df <- read.csv(url2, colClasses=c(fips="character"))

g <- list(
  scope = 'usa',
  projection = list(type = 'albers usa'),
  showlakes = TRUE,
  lakecolor = toRGB('white')
)

plot_ly() %>% 
  add_trace(
    type="choropleth",
    geojson=counties,
    locations=df$fips,
    z=df$unemp,
    colorscale="Viridis",
    zmin=0,
    zmax=12#,
    #marker=list(line=list(width=0))
    ) %>% 
  colorbar(title = "Unemployment Rate (%)") %>% 
  layout( title = "2016 US Unemployment by County") %>% 
  layout(geo = g)

#Scatterplot on Maps

airtraffic <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv')


# geo styling

g <- list(
  scope = 'usa',
  projection = list(type = 'albers usa'),
  showland = TRUE,
  landcolor = toRGB("gray95"),
  subunitcolor = toRGB("gray85"),
  countrycolor = toRGB("gray85"),
  countrywidth = 0.5,
  subunitwidth = 0.5
)


plot_geo(airtraffic, lat = ~lat, lon = ~long) %>% 
  add_markers(
  text = ~paste(airport, city, state, paste("Arrivals:", cnt), sep = "<br />"),
  color = ~cnt, symbol = I("square"), size = I(8), hoverinfo = "text") %>% 
  colorbar(title = "Incoming flights<br />February 2011") %>% 
  layout(title = 'Most trafficked US airports<br />(Hover for airport)', 
           geo = g)

#Explore 3d Charts

Illustrate 3-way interaction of continuous variables

https://plotly.com/r/3d-scatter-plots/

bank <- read.csv('bankdata_emmeans.csv')  
bankmod <- lm(log(currentsalary)~age*experience, data=bank)
summary(bankmod)

Call:
lm(formula = log(currentsalary) ~ age * experience, data = bank)

Residuals:
    Min      1Q  Median      3Q     Max 
-0.9759 -0.2613 -0.0775  0.2610  0.9886 

Coefficients:
                 Estimate Std. Error t value Pr(>|t|)    
(Intercept)    11.5477898  0.0909491 126.970  < 2e-16 ***
age            -0.0232583  0.0026525  -8.769  < 2e-16 ***
experience      0.0562505  0.0111394   5.050 6.34e-07 ***
age:experience -0.0006798  0.0002035  -3.341 0.000902 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.3682 on 470 degrees of freedom
Multiple R-squared:  0.2385,    Adjusted R-squared:  0.2337 
F-statistic: 49.08 on 3 and 470 DF,  p-value: < 2.2e-16
anova(bankmod)
Analysis of Variance Table

Response: log(currentsalary)
                Df Sum Sq Mean Sq F value    Pr(>F)    
age              1 12.547 12.5472  92.553 < 2.2e-16 ***
experience       1  5.901  5.9012  43.529 1.128e-10 ***
age:experience   1  1.513  1.5130  11.161  0.000902 ***
Residuals      470 63.717  0.1356                      
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
library(emmeans)
bankmod.emm <- as.data.frame(emmeans(bankmod, ~age*experience, 
        at=list(age=seq(25, 65, by=5), experience=seq(0, 40, by=5))))

static way to show interaction

ggplot(bankmod.emm, aes(x=age, y=emmean, color=experience, group=experience))+
  geom_line()

the plotly way

plot_ly(bankmod.emm, x = ~age, y = ~experience, z = ~emmean, 
        text = ~paste(lower.CL, '-', upper.CL))
plot_ly(bankmod.emm, x = ~age, y = ~experience, z = ~emmean,  type="mesh3d",
        text = ~paste(lower.CL, '-', upper.CL))
gapm5yr <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv")
        
data_2007 <- gapm5yr[which(gapm5yr$year == 2007),]
data_2007 <- data_2007[order(data_2007$continent, data_2007$country),]
data_2007$size <- data_2007$pop
        
colors <- c('#4AC6B7', '#1972A4', '#965F8A', '#FF7070', '#C61951')
        
plot_ly(data_2007, x = ~gdpPercap, y = ~lifeExp, z = ~pop, 
               color = ~continent, 
              # size = ~size, 
               colors = colors,
               marker = list(symbol = 'circle', sizemode = 'diameter'), 
               sizes = c(5, 150),
               text = ~paste('Country:', country, '<br>Life Expectancy:', lifeExp, '<br>GDP:', gdpPercap,'<br>Pop.:', pop)) %>% 
  layout(title = 'Life Expectancy v. Per Capita GDP, 2007',
         scene = list(xaxis = list(title = 'GDP per capita (2000 dollars)',
                                   gridcolor = 'rgb(255, 255, 255)',
                                   range = c(2.003297660701705, 5.191505530708712),
                                   type = 'log',
                                   zerolinewidth = 1,
                                   ticklen = 5,
                                   gridwidth = 2),
                      yaxis = list(title = 'Life Expectancy (years)',
                                   gridcolor = 'rgb(255, 255, 255)',
                                   range = c(36.12621671352166, 91.72921793264332),
                                   zerolinewidth = 1,
                                   ticklen = 5,
                                   gridwith = 2),
                      zaxis = list(title = 'Population',
                                   gridcolor = 'rgb(255, 255, 255)',
                                   type = 'log',
                                   zerolinewidth = 1,
                                   ticklen = 5,
                                   gridwith = 2)))

Custom controls- wihtout shiny!

https://plotly.com/r/#controls

library(quantmod)
# Download some data
getSymbols(Symbols = c("AAPL", "MSFT"), from = '2018-01-01', to = '2019-01-01')
[1] "AAPL" "MSFT"
ds <- data.frame(Date = index(AAPL), AAPL[,6], MSFT[,6])

plot_ly(ds, x = ~Date) %>% 
  add_lines(y = ~AAPL.Adjusted, name = "Apple") %>%
  add_lines(y = ~MSFT.Adjusted, name = "Microsoft")%>% 
  layout(title = "Stock Prices",
         xaxis = list(
           rangeselector = list(buttons = list(list(count = 3,
                                                    label = "3 mo",
                                                    step = "month",
                                                    stepmode = "backward"),
                                               list(count = 6,
                                                    label = "6 mo",
                                                    step = "month",
                                                    stepmode = "backward"),
                                               list(count = 1,
                                                    label = "1 yr",
                                                    step = "year",
                                                    stepmode = "backward"),
                                               list(count = 1,
                                                    label = "YTD",
                                                    step = "year",
                                                    stepmode = "todate"),
                                               list(step = "all"))),
           rangeslider = list(type = "date")),
         yaxis = list(title = "Price"))

Animations?

https://plotly.com/r/animations/

gapminder  %>%
  plot_ly(x = ~gdpPercap,
          y = ~lifeExp,
          size = ~pop, 
          color = ~continent,
          frame = ~year, 
          text = ~country, 
          hoverinfo = "text",
          type = 'scatter',
          mode = 'markers'
          )%>% 
  layout(xaxis = list(type = "log"))