Wednesday, February 11, 2015

Make your R plots interactive


As a part of my daily job, I draw scatterplots, lots of them. And because there are thousands of genes expressed in any mouse or human tissue, my typical plot looks something like this (code). (Actually, it is a comparison of variance that can be attributed to "sex" factor in mRNA vs. protein expression.)

The question is - what is a gene in the top right corner? And what is the one next to him? And this one? And that?

What we need is a clickable scatterplot. Something I can point with a mouse and get a corresponding gene name. Then click and my browser would open a window with the gene's details (for example in Ensemble). And thanks to ggvis package, it is now possible. Try the following code:

In the case above there must be R running somewhere behind, translating points to gene symbols and Ensemble links. How to share this figure with somebody who does not have R on his or her machine? One possibility is to run it on or your private shiny server.

The second way to add interactive annotation is iplot function in the new Karl Broman's interactive testjs package. It produces Javascipt widget that can be easily saved and share as html page (code).

And with a little help of shiny, we can do even more: Mike Love has a nice example (mtcars_demo in his Github repository), see the widget below. Click on a dot in the left panel makes the corresponding dot in the right panel highlighted (the trick is clickId option in  shiny::plotOutput).

Mike's approach is similar to identify function in basic graphics. The output is a position on an image and you need to find the nearest point afterwards.

I tried something similar with ggvis's SVG objects, so you can set up "on_click" or "on_hoover" events directly (see mtcars_demo here). Click either on left or right panel and the corresponding dot in the opposite panel gets highlighted.

For more complex visualisations, D3.js is a must. However, if you just need to add a bit of interactivity to your R plots, thanks to ggvis, shiny, htmlwidgets, ... it is now possible.

PS. Matt Sundquist sent me the first graph made by plotly that is very cool. More about that maybe later. The trick to edit "on_hover" text is described here.

Variability Explained by Sex