23 Januar 2017

Coursera Project - Using Plotly

This presenatation shows the usage of plotly in a html presentaion using R Markdown. And for fun we add a small interaction.

Todos:

  • create a Markwown file (ioslides_presentation)
  • Init plotly and load dataset
  • create a plot with plotly
  • add some interaction

Init plotly and load dataset

library(plotly)
dataset <- mtcars
head(dataset)
##                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
## Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
## Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
## Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
## Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
## Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
## Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

create a plot with plotly

Here is a simple scatter plot with plotly.

plot_ly(dataset, x= ~wt, y=~mpg,type = "scatter", 
        mode ="markers", color = ~as.factor(cyl))

add some interaction

Now we can add some "interaction'.

For this, we add a quick-and-dirty java-script:

<script type="text/javascript">
    function toggle_selected() {
        var x = document.getElementById("myselect").value;
       document.getElementById("wt_mpg").style.display = 'none';
       document.getElementById("hp_mpg").style.display = 'none';
       document.getElementById("qsec_mpg").style.display = 'none';
       document.getElementById(x).style.display = 'block';
    }
</script>

add some interaction

.. and a html select component and div's with the plots to show:

<select id="myselect" onchange="toggle_selected()">
  <option value="wt_mpg">wt ~ mpg</option>  
  <option value="hp_mpg">hp ~ mpg</option>
  <option value="qsec_mpg">qsec ~ mpg</option>
</select> 

<div id = "wt_mpg" style="display: block" > R-Code-Block </div>
<div id = "hp_mpg" style="display: none" > R-Code-Block </div>
<div id = "qsec_mpg" style="display: none" > R-Code-Block </div>

add some interaction

.. And voila, a bit of "interaction"

select Plot: