May 2, 2017

R Markdown Presentation & Plotly

Create a web page presentation using R Markdown that features a plot created with Plotly. Host your webpage on either GitHub Pages, RPubs, or NeoCities. Your webpage must contain the date that you created the document, and it must contain a plot created with Plotly.

Examine the structure of the dataset

str(mtcars)
'data.frame':   32 obs. of  11 variables:
 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: num  4 4 1 1 2 1 4 2 2 4 ...
# add a new column
mtcars$trans <- ifelse(mtcars$am == 0,"automatic", "manual" )

Plotly in action example 1

R code

library(plotly)
plot_ly(mtcars, 
        x = ~hp, 
        y = ~mpg,
        color = ~as.factor(cyl), 
        type = "scatter",
        mode = "marker",
        marker = list(size = 10),
        dragmode = "zoom",
        hoverinfo = "text",
        text = ~paste("Weight: ", wt, 
                      "</br> Gear: ", gear,
                      "</br> Carb: ", carb,
                      "</br> Cylinders: ", cyl,
                      "</br> Transmission: ", trans,
                      "</br> Car Model: ", rownames(mtcars))) %>%
      layout(title = "Miles Per Gallon vs Horse Power", showlegend = T) %>%
      layout(yaxis = list(title = "Miles Per Gallon"), 
             xaxis = list(title = "Horse Power"))

Plotly in action example 1

Plotly in action example 2

R code

plot_ly(mtcars, 
        y = ~mpg, 
        color = ~as.factor(cyl), 
        type = "box") %>%
      layout(title = "Miles per Gallon for\n Different Cylinders", 
             showlegend = T) %>%
      layout(yaxis = list(title = "Miles Per Gallon"), 
             xaxis = list(title = "Number of Cylinders"))

Plotly in action 2

Plotly in action example 3

R code

plot_ly(mtcars, 
        y = ~mpg, 
        color = ~trans, 
        type = "box") %>%
      layout(title = "Miles per Gallon for\nAutomatic and Manual Transmission Cars", 
             showlegend = T) %>%
      layout(yaxis = list(title = "Miles Per Gallon", 
                          showticklabels = T))

Plotly in action 3